TWO BIG WORDS Inheritance Defining a class that
TWO BIG WORDS • Inheritance • Defining a class that, by default, has all the same behavior of some other (parent) class • We can re-define some of the parent functions/attributes • We can add new behaviors and attributes to supplement the original • Polymorphism • We can take advantage of the fact that all of a certain set of classes have common attributes/behaviors • Can avoid redundancy by specifying requirements to be in the particular class
SUBCLASSES • Used to add member functions/attributes to existing classes, without modifying the original • Syntax:
SUBCLASSES • Naturally, we can apply the same principle to subclasses, extending them further • This creates a class-hierarchy
SUBCLASSES • In the left diagram: • A is the superclass of B, C, D, and E • All others have all members of A • B, C, and D share existing attributes/behaviors of A, but may have totally independent features • E inherits from both D and A
SUBCLASSES • Example: vehicle database • What are the defining attributes of a vehicle? • Color • Make • Model • Number of wheels • Variable, but can also be an indication of more fine-grained classification (see right)
VEHICLES • Idea: • Define the vehicle class to have the attribute: • int number. Of. Wheels; • In the subclasses, we can specify exactly how many in the constructor or class definition • Can add more specific attributes: • Car: number. Of. Doors • Truck: number. Of. Axels • Motorcycle: has. Side. Car
CLASS AND SUBCLASS VARIABLES • Very Important Fact • An variable that can hold a reference to an object of class A can also hold a reference to an object of any subclass of A. • E. g. if “Car” is a subclass of “Vehicle”, the following is legal: Vehicle v; Car c = new Car(); v = c; // We don’t even lose the Car information!
POLYMORPHISM • With some planning, we can use some objects/classes in our program without knowing exactly what they are at runtime (!!!) • Recall that: 1. Very Important Fact: any variable that holds a reference to a class can also hold a reference to any of its subclasses 2. Subclasses can override base class members
POLYMORPHISM • Architectural idea • Write functions to accept the most general type of parameter possible, assuming all subclasses have responsibly overridden any necessary methods • We have seen this already in the form of the Object. to. String() method override!
POLYMORPHISM • Example: • In our vehicle example: make sure each vehicle defines its own “print()” method • Add a method in the driver class to call “. print()” on a Vehicle parameter • Example 2: • Add an “upgrade()” method to the Vehicle class • Do nothing • Override in each subclass, upgrading where appropriate • Upgrade some vehicles, then print
- Slides: 10