Download presentation
Presentation is loading. Please wait.
Published byIsaac Jones Modified over 8 years ago
1
Lecture 6: Composition and Inheritance CS202 Fall 2013
2
Composition Compose: to create something by combining other things In programming, Composition occurs when a class includes variables of other classes We have been doing this all along whenever we write classes that contain Strings or Scanners. Several of the lecture examples have contained variables that referred to objects of classes defined in the examples. – GradeBook above contains an array list of Students – CollegeDriver from lecture 5 contained an array list of departments, and each department contained an array list of Courses Hierarchies like this can be of any depth. Double contains a compareTo() method. Since Student.gpa is a Double, Student.compareTo() could have been written this way: – return this.gpa.compareTo(otherStudent.gpa);
3
Inheritance 3 Classes often have natural hierarchies, which can be defined in terms of data or in terms of functionality The simplest form of hierarchy is general-to- specific
4
Inheritance 4 All vehicles have some variables in common – weight – source of locomotion – manufacturer Motor vehicles are a subset of vehicles, and they have additional data fields – Engine displacement – Fuel type Trucks are a subset of motor vehicles, and they have yet more data fields – Hauling capacity – Etc
5
Inheritance We can model this kind of general-to-specific hierarchy using class inheritance “Super” means above, as in supervisor. “Sub” means under or below, as in submarine. A subclass is a class which is a more specific form of some other class, which we call its superclass Superclasses are more abstract than their subclasses The terms parent and child are sometimes used in place of superclass and subclass. To define a class as a subclass of a superclass, use the extends keyword. See the examples below
6
Inheritance Hierarchy A class can inherit from a hierarchy of superclasses, in the same way you have parents, grandparents, great-grandparents, etc. All Java classes are subclasses of Object. Object is, for example, where the original forms of toString() is defined. However, most other classes do not inherit directly from Object. – Here is the class hierarchy for OutOfMemoryError java.lang.Object java.lang.Throwable java.lang.Error java.lang.VirtualMachineError java.lang.OutOfMemoryError
7
Inheritance Subclasses inherit the methods and variables of their superclasses. Subclasses can add variables, constants, and methods which are not present in their superclasses.
8
Overriding Subclasses can also replace methods inherited from superclasses with their own methods. This is called overriding. – toString()! – Use the @Override annotation – Make the superclass methods public or protected; can’t override private methods Subclass constructors call superclass constructors. If superclass has a no-argument constructor, it is called by default by a no-argument subclass constructor – See example
9
Single Inheritance C++ allows a class to have more than one parent class. This is called “multiple inheritance”. Most programmers find this confusing. – The superclasses might have variables or methods with the same names In Java, a class is allowed to inherit from only one parent class. This is called “single inheritance”
10
Inheritance package vehicles; public class Vehicle { protected double weightInKg; protected double speedInKmPerHr; protected Direction direction; public Vehicle() { } public Vehicle(double weightInKgIn, double speedIn) { weightInKg = weightInKgIn; speedInKmPerHr = speedIn; direction = new Direction(0, 0); } public void steer(double bearing, double angle) { direction.setDirection(bearing, angle); } public void accelerate(double speedIncrement) { speedInKmPerHr += speedIncrement; } public String toString() { return "vehicle weighs " + weightInKg + " kg: is going " + speedInKmPerHr + ": " + direction.toString(); }
11
Inheritance package vehicles; public class Direction { private double bearing, angleToGround; public Direction(double bearingIn, double angleIn){ bearing = bearingIn; angleToGround = angleIn; } public void setDirection(double bearingIn, double angleIn){ bearing = bearingIn; angleToGround = angleIn; } // setters and getters omitted public String toString(){ return "Bearing: " + bearing + ": Angle: " + angleToGround; }
12
Inheritance package vehicles; public class MotorVehicle extends Vehicle { private double engineDisplacementInCc; private String fuelType; public MotorVehicle() { // this one implicitly calls Vehicle's constructor } public MotorVehicle(double weightInKgIn, double speedIn, double displacementIn, String fuelTypeIn) { super(weightInKgIn, speedIn); engineDisplacementInCc = displacementIn; fuelType = fuelTypeIn; } // also override steer() to change direction in a way appropriate for a car // getters and setters omitted public String toString() { return "engine displacement; " + engineDisplacementInCc + ": fuelType; " + fuelType + ": " + super.toString(); }
13
Inheritance package vehicles; public class Car extends MotorVehicle { private double throttleSetting; private String manufacturer; public Car(double weightInKgIn, double speedIn, double displacementIn, String fuelTypeIn, String manufacturerIn) { super(weightInKgIn, speedIn, displacementIn, fuelTypeIn); manufacturer = manufacturerIn; throttleSetting = 0; } @Override public void accelerate(double speedIncrement) { double origSpeed = speedInKmPerHr; while (speedInKmPerHr < origSpeed + speedIncrement && throttleSetting <= 10) { graduallyOpenThrottle(speedIncrement); } // then close the throttle a little, etc. } private void graduallyOpenThrottle(double speedIncrement) { // use your imagination. This is a cheap example throttleSetting = 3; speedInKmPerHr += speedIncrement; } public String toString() { return "Manufacturer; " + manufacturer + ": throttle; " + throttleSetting + ": " + super.toString(); }
14
Inheritance package vehicles; public class Driver { public static void main(String[] args) { Car shredder = new Car(1000, 100, 2400, "gasoline", "Mazda"); System.out.println(shredder); shredder.accelerate(20); shredder.steer(270, 15); System.out.println(shredder); }
15
Inheritance 15 Concrete means particular or tangible, not abstract. – Originally meant solidified or hardened. The building material was named because it has this quality The classes in the previous examples were concrete classes, ones that can be instantiated
16
Inheritance 16 Classes may be abstract – An abstract class cannot be instantiated, but it can have subclasses that are concrete. Abstract classes may contain data fields that will be common to all subclasses
17
Inheritance 17 Abstract classes may define concrete methods, but they may also declare abstract methods – An abstract method isn't defined (written) in the class, but must be defined in a subclass Subclasses that are also abstract can define the method or ignore it, leaving it to be defined in their own subclasses. A concrete class may inherit or override concrete method definitions from its superclass(es) A concrete class must define any methods which are abstract in its superclass hierarchy
18
Inheritance 18 Syntax for abstract method: access modifier abstract return type name(); For example: protected abstract void accelerate(double speedIncrement); Syntax to implement a method that is abstract in the superclass: – Just add @Override notation above the method code: @Override protected void accelerate(double speedIncrement){ speedInKmPerHr+=speedIncrement; }
19
Inheritance 19 Use an abstract class when you expect to create subclasses that will implement some methods identically but other methods in different ways. If you don’t need any data fields and don’t need to define any methods, use an interface (next week!) instead. Implementation of multiple subclasses of the same class is another form of polymorphism.
20
Inheritance 20 package vehicles; public class Direction { private double bearing, angleToGround; public Direction(){} public Direction(double bearingIn, double angleIn){ bearing = bearingIn; angleToGround = angleIn; } public void setDirection(double bearingIn, double angleIn){ bearing = bearingIn; angleToGround = angleIn; } public String toString(){ return "Bearing: " + bearing + ": Angle: " + angleToGround; }
21
Inheritance 21 package vehicles; public abstract class Vehicle { protected double weightInKg; protected double speedInKmPerHr; protected Direction direction; protected abstract void accelerate(double speedIncrement); protected abstract void register(); protected abstract void steer(double bearing, double angle); }
22
Inheritance 22 package vehicles; public abstract class MotorVehicle extends Vehicle { protected double engineDisplacementInCc; protected String fuelType; protected String manufacturer; public void register() { System.out.println("Registered " + manufacturer + " vehicle with DMV"); }
23
Inheritance 23 package vehicles; public class Car extends MotorVehicle { public Car(String manufacturerIn, double weightInKgIn, double displacementIn, String fuelTypeIn){ manufacturer=manufacturerIn; weightInKg = weightInKgIn; engineDisplacementInCc = displacementIn; fuelType = fuelTypeIn; speedInKmPerHr = 0; direction = new Direction(); } @Override protected void steer(double bearing, double angle) { // replace the following with code to steer a car direction = new Direction(bearing, angle); } @Override protected void accelerate(double speedIncrement) { // replace the following with code to accelerate like a car speedInKmPerHr += speedIncrement; } public String toString() { return manufacturer + " car with a " + engineDisplacementInCc + " cc " + fuelType + " engine weighs " + weightInKg + " kg and is going " + speedInKmPerHr +" KPH " + direction.toString(); }
24
Inheritance 24 package vehicles; public class Motorcycle extends MotorVehicle { public Motorcycle(String manufacturerIn, double weightInKgIn, double displacementIn, String fuelTypeIn){ manufacturer=manufacturerIn; weightInKg = weightInKgIn; engineDisplacementInCc = displacementIn; fuelType = fuelTypeIn; speedInKmPerHr = 0; direction = new Direction(); } public Motorcycle(String manufacturerIn, double weightInKgIn, double displacementIn){ manufacturer=manufacturerIn; weightInKg = weightInKgIn; engineDisplacementInCc = displacementIn; fuelType = "gasoline"; speedInKmPerHr = 0; direction = new Direction(); } @Override protected void accelerate(double speedIncrement) { // replace the following with code to accelerate like a motorcycle speedInKmPerHr += speedIncrement; } @Override protected void steer(double bearing, double angle) { // replace the following with code to steer a motorcycle direction=new Direction(bearing, angle); } public String toString() { return manufacturer + " motorcycle with a " + engineDisplacementInCc + " cc " + fuelType + " engine weighs " + weightInKg + " kg and is going " + speedInKmPerHr +" KPH " + direction.toString(); }
25
Inheritance 25 package vehicles; public abstract class Spacecraft extends Vehicle { // this class could have a hierarchy of abstract and concrete classes under it }
26
Inheritance 26 package vehicles; public class Driver { public static void main(String[] args) { Vehicle shredder = new Car("Mazda", 1000, 1900, "gasoline"); System.out.println(shredder); shredder.register(); shredder.accelerate(20); shredder.steer(270, 0); System.out.println(shredder); System.out.println(); Vehicle hindenburg = new Motorcycle("BMW", 230, 594, "gasoline"); hindenburg.steer(70, 0); hindenburg.accelerate(90); System.out.println(hindenburg); System.out.println(); Vehicle porky = new Motorcycle("Harley-Davidson", 400, 1200); porky.accelerate(150); porky.steer(180, 45); System.out.println(porky); }
27
Inheritance 27 You can't instantiate an abstract class:
28
Inheritance 28 A concrete class must have a definition for each inherited method. If the method was abstract in the last superclass, it must be defined in the new class:
29
More On Inheritance 29 Usually a bad idea
30
Inheritance 30 You can use a reference variable to get access to public methods of the variable's type and supertypes. Using methods of subtypes of the variable's type requires a cast and is usually a bad idea. This is true even though you instantiate an object of the subclass and make the variable reference it. public class Motorcycle extends MotorVehicle { private boolean sidecarPresent; … stuff omitted public void installSidecar(){ // this is a method of motorcycle. Its superclasses don't know about it sidecarPresent = true; } …
31
Inheritance 31 These are both dicy ideas!
32
Inheritance 32 Our hierarchy of abstraction is getting complicated: – An object has actual data values. It is less abstract than the class of which it is an instance – A concrete class doesn’t have data values (except constants), so it is more abstract than an object. However, all of its methods are defined, whether they were inherited from the superclass(es) or are written in the method itself, so it is less abstract than any superclass(es) it might have – We may have concrete superclasses, which are more abstract than their subclasses – Abstract classes are, as the name suggests, more abstract than concrete classes. They usually have methods that must be defined in their subclasses. Even if they don’t, they can never be instantiated; only their subclasses can. For these reasons, they are more abstract than concrete classes. – We may have a hierarchy of abstract superclasses. – Every class is a subclass of Object
33
.jar files.jar files are used for distributing Java applications and libraries. The file format is.zip, but the extension.jar identifies them as Java Archives They contain bytecode (.class files), any other files from the application or library (like images or audio files), and can also contain source code The JDK contains command line tools for making jar files, but this is easier to do with Eclipse Jar files may be executable, meaning that they are configured to launch the main() of some class contained in the jar
34
.jar files
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.