Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 6: Composition and Inheritance

Similar presentations


Presentation on theme: "Lecture 6: Composition and Inheritance"— Presentation transcript:

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 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.

3 Inheritance 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 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 annotation Superclass methods must be 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”. This can lead to namepsace conflicts, in which multiple methods or variables with identical names would be in scope at the same time without complex precedence rules. 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 = 0; // a new vehicle should stop after it rolls off the assembly line protected Direction direction = new Direction(); // avoid null pointer exceptions by giving new vehicle the default direction 0, 0, 0 public Vehicle() { } public Vehicle(double weightInKgIn) { weightInKg = weightInKgIn; public void steer(double bearing, double z) { direction.setDirection(bearing, z); 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, z; public Direction(){} public Direction(double bearingIn, double zIn){ setDirection(bearing, z); } public void setDirection(double bearingIn, double zIn){ bearing = bearingIn; z = zIn; public double getBearing() { return bearing; public double getZ() { return z; public String toString(){ return "bearing: " + bearing + ": z: " + z;

12 Inheritance package vehicles; public class MotorVehicle extends Vehicle { protected double engineDisplacementInCc; protected String fuelType; protected String manufacturer; public MotorVehicle(){} public MotorVehicle(double weightInKgIn, String manufacturerIn, double displacementIn, String fuelTypeIn) { super(weightInKgIn); manufacturer = manufacturerIn; engineDisplacementInCc = displacementIn; fuelType = fuelTypeIn; } public double getEngineDisplacementInCc() { return engineDisplacementInCc; public String getFuelType() { return fuelType; public String getManufacturer() { return manufacturer; // this method is unique to MotorVehicles, not common to all vehicles public void register() { System.out.println("Registered " + manufacturer + " vehicle with DMV"); public String toString() { return "manufacturer: " + manufacturer + "engine displacement: " + engineDisplacementInCc + ": fuelType: " + fuelType + ": " + super.toString();

13 Inheritance package vehicles; public class Car extends MotorVehicle { private String licensePlateNumber; public Car(double weightInKgIn, String manufacturerIn, double displacementIn, String fuelTypeIn, String licensePlateNumberIn){ super(weightInKgIn, manufacturerIn, displacementIn, fuelTypeIn); licensePlateNumber = licensePlateNumberIn; } public String getLicensePlateNumber() { return licensePlateNumber; public void setLicensePlateNumber(String licensePlateNumber) { this.licensePlateNumber = licensePlateNumber; public String toString() { return manufacturer + " car with plate " + licensePlateNumber + " and engine displacement " + engineDisplacementInCc + " cc " + fuelType + " engine weighs " + weightInKg + " kg and is going " + speedInKmPerHr +" KPH " + direction.toString();

14 Inheritance package vehicles; public class Motorcycle extends MotorVehicle { private double volumeInDecibels; public Motorcycle(double weightInKgIn, String manufacturerIn, double displacementIn, double volumeInDecibelsIn) { super(); // note the difference between these assignments and the way the same task is done in the Car constructor. // This way is simpler, but might miss or require duplication of initialization logic in the superclass constructors. manufacturer = manufacturerIn; weightInKg = weightInKgIn; engineDisplacementInCc = displacementIn; fuelType = "gasoline"; speedInKmPerHr = 0; volumeInDecibels = volumeInDecibelsIn; } public double getVolumeInDecibels() { return volumeInDecibels; public void setVolumeInDecibels(double volumeInDecibels) { this.volumeInDecibels = volumeInDecibels; public String toString() { return manufacturer + " motorcycle with a " + engineDisplacementInCc + " cc " + fuelType + " engine weighs " + weightInKg + " kg and is going " + speedInKmPerHr + " KPH " + direction.toString() + " making noise at " + volumeInDecibels + " db";

15 Inheritance package vehicles; public class Driver { public static void main(String[] args) { Vehicle shredder = new Car(1000, "Mazda", 1900, "gasoline", "ABC-123"); System.out.println(shredder); shredder.accelerate(20); shredder.steer(100, 0); System.out.println(); Vehicle hindenburg = new Motorcycle(240, "BMW", 594, 80); hindenburg.steer(70, 0); hindenburg.accelerate(90); System.out.println(hindenburg); Vehicle porky = new Motorcycle(400, "Harley-Davidson", 1200, 150); porky.accelerate(150); porky.steer(180, 45); System.out.println(porky); }

16 Inheritance 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

17 Inheritance 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

18 Inheritance 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

19 Inheritance 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 notation above the method code: @Override protected void accelerate(double speedIncrement){ speedInKmPerHr+=speedIncrement; }

20 Inheritance 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.

21 Inheritance package vehicles; public abstract class Vehicle { protected double weightInKg; protected double speedInKmPerHr = 0; // a new vehicle should stop after it rolls off the assembly line protected Direction direction = new Direction(); // avoid null pointer exceptions by giving new vehicle the default direction 0, 0, 0 public Vehicle() { } public Vehicle(double weightInKgIn) { weightInKg = weightInKgIn; public abstract void steer(double bearing, double z); public abstract void accelerate(double speedIncrement); public String toString() { return "vehicle weighs " + weightInKg + " kg: is going " + speedInKmPerHr + ": " + direction.toString();

22 Inheritance package vehicleswithabstractclass; public abstract class MotorVehicle extends Vehicle { protected double engineDisplacementInCc; protected String fuelType; protected String manufacturer; public MotorVehicle(){} public MotorVehicle(double weightInKgIn, String manufacturerIn, double displacementIn, String fuelTypeIn) { super(weightInKgIn); manufacturer = manufacturerIn; engineDisplacementInCc = displacementIn; fuelType = fuelTypeIn; } public double getEngineDisplacementInCc() { return engineDisplacementInCc; public String getFuelType() { return fuelType; public String getManufacturer() { return manufacturer; // this method is unique to MotorVehicles, not common to all vehicles public void register() { System.out.println("Registered " + manufacturer + " vehicle with DMV"); public String toString() { return "manufacturer: " + manufacturer + "engine displacement: " + engineDisplacementInCc + ": fuelType: " + fuelType + ": " + public void steer(double bearing, double z) { // supply code to steer like a motor vehicle // accelerate() is still abstract here

23 Inheritance package vehicleswithabstractclass; public class Car extends MotorVehicle { private String licensePlateNumber; public Car(double weightInKgIn, String manufacturerIn, double displacementIn, String fuelTypeIn, String licensePlateNumberIn){ super(weightInKgIn, manufacturerIn, displacementIn, fuelTypeIn); licensePlateNumber = licensePlateNumberIn; } public String getLicensePlateNumber() { return licensePlateNumber; public void setLicensePlateNumber(String licensePlateNumber) { this.licensePlateNumber = licensePlateNumber; public String toString() { return manufacturer + " car with plate " + licensePlateNumber + " and engine displacement " + engineDisplacementInCc + " cc " + fuelType + " engine weighs " + weightInKg + " kg and is going " + speedInKmPerHr +" KPH " + public void accelerate(double speedIncrement) { // supply code to accelerate like a car

24 Inheritance package vehicleswithabstractclass; public class Motorcycle extends MotorVehicle { private double volumeInDecibels; public Motorcycle(double weightInKgIn, String manufacturerIn, double displacementIn, double volumeInDecibelsIn) { super(); // note the difference between these assignments and the way the same task is done in the Car constructor. // This way is simpler, but might miss or require duplication of initialization logic in the superclass constructors. manufacturer = manufacturerIn; weightInKg = weightInKgIn; engineDisplacementInCc = displacementIn; fuelType = "gasoline"; speedInKmPerHr = 0; volumeInDecibels = volumeInDecibelsIn; } public double getVolumeInDecibels() { return volumeInDecibels; public void setVolumeInDecibels(double volumeInDecibels) { this.volumeInDecibels = volumeInDecibels; public String toString() { return manufacturer + " motorcycle with a " + engineDisplacementInCc + " cc " + fuelType + " engine weighs " + weightInKg + " kg and is going " + speedInKmPerHr + " KPH " + direction.toString() + " making noise at " + volumeInDecibels + " public void accelerate(double speedIncrement) { // accelerate like a motorcycle

25 Inheritance package vehicles; public abstract class Spacecraft extends Vehicle { // this class could have a hierarchy of abstract and concrete classes under it }

26 Inheritance package vehicleswithabstractclass; public class Driver { public static void main(String[] args) { Vehicle shredder = new Car(1000, "Mazda", 1900, "gasoline", "ABC-123"); System.out.println(shredder); shredder.accelerate(20); shredder.steer(100, 0); System.out.println(); Vehicle hindenburg = new Motorcycle(240, "BMW", 594, 80); hindenburg.steer(70, 0); hindenburg.accelerate(90); System.out.println(hindenburg); Vehicle porky = new Motorcycle(400, "Harley-Davidson", 1200, 150); porky.accelerate(150); porky.steer(180, 45); System.out.println(porky); }

27 Inheritance You can't instantiate an abstract class:

28 Inheritance 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 Usually a bad idea

30 Inheritance 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 These are both dicy ideas!

32 Inheritance 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


Download ppt "Lecture 6: Composition and Inheritance"

Similar presentations


Ads by Google