310 likes | 469 Views
INHERITANCE Class Hierarchies Extending Objects Abstract Methods Abstract Classes Overriding Methods protected. Everyone wants a car nowadays. Remember the CSMobile? sufficient for driving around town But what about camping trips?
E N D
INHERITANCE • Class Hierarchies • Extending Objects • Abstract Methods • Abstract Classes • Overriding Methods • protected
Everyone wants a car nowadays • Remember the CSMobile? • sufficient for driving around town • But what about camping trips? - need a van, a vehicle that’s big enough to hold more passengers, and all the camping gear • And what if you want to look sharp? • need to get places in a hurry • like driving with the top down • So, need a convertible sportscar that moves fast
Similarities and Differences • What do these three vehicles have in common? • they’re all cars! • all can move • all have an engine • all have doors • all have one driver • all hold a number of passengers • What about these three vehicles is different? • the sportscar: • convertible top, 2 doors, moves really fast, holds small number of people • the van: • high top, 5 doors (one of which slides open), moves at moderate speed, holds large number of people • the CSMobile: • normal top, 2 doors, moves slowly, holds moderate number of people
Inheritance Animal Reptile Mammal Fish Dog Cat Moose • Inheritance models “is a” relationships • object “is an” other object if it can behave in the same way • Inheritance uses similarities and differences to model groups of related objects • Where there’s Inheritance, there’s an Inheritance Hierarchy of classes • Mammal “is an” Animal • Cat “is a” Mammal • transitive: a Cat “is an” Animal, too • We can say: • Reptile, Mammal and Fish “inherit from” Animal • Dog, Cat, andMoose “inherit from” Mammal
Car SportsCar Van CSMobile Inheritance, even in the car industry! • Wow! What does this have to do with cars? • a SportsCar “is a” Car • a CSMobile “is a” Car • you get the picture... • We call this a tree diagram, with Car as the “root” and SportsCar, CSMobile, Van as “leaves” (yes, it’s an upside down tree . . .) • How can this help Andy and the TAs? • First let’s discuss some important facts about Inheritance
Superclasses and Subclasses • Inheritance is a way of: • organizing information • grouping similar classes • modeling similarities between classes • creating a taxonomy of objects • Animal is called superclass • or base class or parent class • in car example, Car is called superclass • Fish is called subclass • or derived class or child class • in car example, SportsCar is subclass • Any class can be both at same time • e.g., Mammalis superclass of Moose and subclass of Animal • Can only inherit from one superclass in Java • otherwise, no limit to depth or breadth of class hierarchy • C++ allows a subclass to inherit from multiple superclasses (error-prone)
Inheriting Capabilities and Properties • Subclass inheritsall public capabilities of its superclass • if Animals eat and sleep, then Reptiles, Mammals and Fish eat and sleep • ifCars move, then SportsCars move! • anything superclass can do, subclass can do • Subclass specializes its superclass • by adding new methods, overridingexisting methods, and defining “abstract”methodsdeclared by parent • we’ll see this in a few slides! • Superclass factors out capabilities common to its subclasses • subclasses described by differences from superclass • As a general pattern, subclasses: • inherit public capabilities (methods) • inherit private properties (instance variables) but do not have access • so can subclasses inherit variables that they CAN access?
protectedInstance Variables • Answer: subclasses inherit protected variables and can access them! • A variable that is declared protected by a superclass becomes part of the inheritance • variable becomes available for subclasses to access as if it were their own • in contrast, if an instance variable is declared private by a superclass, its subclasses won’t have access to it • superclass could still provide protected access to its private instance variables via accessor and mutator methods • How can I decide between private and protected? • use private if you want an instance variable to be encapsulated by superclass • e.g., doors, windows, spark plugs • use protected if you want an instance variable to be available for subclasses to change (and you don’t want to make the variable more generally accessible via accessor/mutator methods) • e.g., engine, so that subclasses can soup it up!
Student CollegeStudent CSstudent Inheritance Example • Studentinheritance hierarchy: • Student as baseclass • CollegeStudent as Student’s subclass • CSstudent as subclass of CollegeStudent • Student has one capability (or method) • study() which works by: • going home, opening a book, and reading 50 pages.
Inheritance Example (cont.) • CollegeStudent “is a” Student, so inherits study() • But it overrides the study() method to work by: • going to the library, studying for a midterm, and doing a problem set • Finally the CSstudent also knows how to study() (it study()s the same way a CollegeStudent does) • However adds two capabilities: gitDown() and gitFunky() • public void gitDown() { // Code to party } • public void gitFunky() { // Code to do awesome CS dance } • Each subclass specializes its superclass • Student knows how to study(), so all subclasses in hierarchy know how to study() • But the CollegeStudent does not study() the same way a Student does • And the CSstudent has some capabilities that neither Student nor CollegeStudent have (gitDown() and gitFunky())
Inheritance as Form of Abstraction • Root of class hierarchy is most general object because it is superclass to every other object in hierarchy • can always say much more about how a subclass behaves than how its superclass behaves • e.g., can say more about how a Van behaves than how a Car behaves!
Inherit This! 5 things you might find in an Inheritance Hierarchy: 1) superclass is too general to declare all behavior, so each subclass adds its own behavior 2) superclass legislates an abstractbehaviorand therefore delegates implementation to subclasses • (see upcoming move method) 3) superclass specifies behavior, subclasses inherit behavior • (see upcoming startEngine method) 4) superclass specifies behavior, subclasses choose to override behavior • just because a subclass inherits a method, doesn’t mean that it must act in the same way as its superclass • subclass can choose to reject its superclass’ implementation of any method and “do it my way” 5) superclass specifies behavior, subclasses choose to override behavior in part • called partial overriding • you’ll learn this next lecture!
Abstract Methods • What if we know that all subclasses should have some capability, yet we don’t know how those subclasses will implement it? • e.g., all Cars know how to move, but each moves differently • There would be nocode that could be written for that capability that would apply to every subclass • Methods for which no implementation makes sense should be abstract • abstract means it has no definition, only declaration • declaration highlights important features of method - its name, class of instance it returns (or none), and number and class of its parameters (if any) • this information comprises what is known as the method’s “signature”
Abstract Methods, continued • Reserved word abstract is modifierthat says everysubclass has specific capability, but superclass is unaware of implementationof that capability • superclass defines policy for subclasses to implement • guarantees some subclass down in the hierarchy will implement method • Although abstract methods have no implementation, they are not the same as empty methods • can’t instantiate an abstract class, i.e., a class that has one or more abstract methods • can instantiate a class with an empty method • most empty methods that you’ll see will be constructors • empty methods still need curly braces, abstract methods must not have curly braces, instead they must end in a semi-colon • public void emptyMethod() { } • abstract public void abstractMethod(); • Any class which contains an abstractmethod mustitself be declared abstract
Abstract Classes • Possible definition of Car • all Cars can move, • but superclass does not say how • superclass simply declares abstract methods, subclass must define all abstract methods in order to become concrete • Abstract classes cannot be instantiated • Once subclass has defined all abstractmethods it can be instantiated • it is concrete! publicabstractclass Car { // define to provide moving behavior abstractpublic void move(); } note the semicolon! // This will not compile. Car myCar = new Car();
Code: Let’s make some Cars! (1 of 3) publicabstractclass Car { // properties of all Cars private Door _driverDoor; // protected, because subclasses // might want to soup up their Engine protected Engine _engine; // more properties go here public Car() { _driverDoor = new Door(); // initialize other variables here } // notice the semicolon at the end of the // abstract method declaration! This is // important! public abstract void move(); public void startEngine() { // code to start up engine } // more methods go here } // end of class Car What’s the difference between move and startEngine?
Code: Let’s make some Cars! (2 of 3) - Now that we are defining move(), it looks like any other method public class Van extends Car { public Van() { super(); } public void move() { // code to move at a moderate speed } } // end of class Van public class CSMobile extends Car { public CSMobile() { super(); } public void move() { // code to just pitter along! } } // end of class CSMobile Note that neither Van nor CSMobile include the startEngine method. Think about what this means…
Code: Let’s make some Cars! (3 of 3) public class SportsCarextendsCar { private ConvertibleTop _top; // more properties here public SportsCar() { super(); _top = new ConvertibleTop(); // initialize other variables here } public void move() { // code to move really fast } public void startEngine() { // code to start engine with the // gusto of a SportsCar! Vroom! } } // end of class SportsCar
Syntax: Declaring/Defining a Subclass • To declare subclass of Car, we say that it extendssuperclass public class SportsCar extends Car • Now, let’s look at constructor definition for SportsCar: public SportsCar() { super(); _top = new ConvertibleTop(); } • What’s going on inside SportsCar’s constructor?
Superclass Constructors • SportsCar is responsible for initializing instance variables it defines: _top = new ConvertibleTop(); • ConvertibleTop is a property specific to SportsCars, so it is initialized in the constructor for SportsCar • Likewise, Caris responsible for initializing its instance variables. • some are private and encapsulated • some are protected, so subclasses can use them! • So... must call SportsCar’s constructor and Car’s constructor • to make sure any inherited instance variables are initialized! • How can I do that? Always have subclass constructor call superclass constructor! • Note that the abstract superclass, Car, isn’t explicitly instantiated and only a subclass uses the superclass’ constructor
Syntax: superclass Constructors • Use reserved word superto call superclass constructor • it is as if superclass’ name issuper and you are calling its constructor (i.e., calling method with same name as class) public SportsCar() { super(); // rest of constructor elided } • You’ll always use this pattern: • call to superclass constructor must be first line of subclass constructor • calling superclass constructor anywhere else is compile-time error • because initializing subclass may presuppose initialized superclass • then initialize any subclass instance variables • In fact, is exactly the default constructor Java provides every class automatically • don’t have to call super(); but a good habit { super(); }
super and Parameters • In our example, Car takes no parameters in its constructor public Car() nothing between the parentheses! • What if Car had a constructor that needed parameters to be passed to it? public Car(Driver driver) this Car expects a Driver! • Then SportsCar needs to pass Car’s constructor a Driver • so either SportsCar needs to create a Driver, or needs to take one as parameter public SportsCar(Driver driver) this SportsCar expects a Driver!
super and Parameters (continued) • public SportsCar(Driver driver) { super(driver); } this SportsCar gets a Driver and passes it up to its superclass’ constructor! • Note again that only a subclass will invoke the abstract superclass’ constructor and pass it its parameters • What happens if you forget to call the superclass constructor here? • Java automatically calls super(); for you • But... latest definition for Car doesn’t have a constructor that takes no parameters • So... Compile Error. Java complains that there is no constructor declared public Car()
Overriding (Redefining) Methods • Subclasses can override, i.e., redefine inherited methods: • can choose to reject their superclass’ implementation of any method • this means they can write their own definitions for how to respond to messages sent to them • Car declares a startEngine() method that subclasses can either inherit (not change) or override (change) public class SportsCar extends Car { // declarations and constructor elided public void startEngine() { // code to start engine with the gusto of // a SportsCar! Vroom! } } • Definition of startEnginereplacesthe one in superclass • must be declared identically (in name and parameter list!) — check documentation • otherwise, nothing special about declaration
How does Java call methods? • We can use Vanin the same way we would use Car • because it behaves like the superclass in that it responds to the same messages • How does Java determine which method to call when move() message is sent to instance? • this is where class of instance is important • when instance of Vanis created, its class determines which methods will be called
Method Resolution • First, Java sees if instance’s class defines the method; if so, calls it • If not, Java “walks up class inheritance tree” from subclass to superclass until it either • finds method, in which case it calls inherited method • doesn’t find method; this is compile-time error (sending message for which there is no method) • This process is called method resolution. • for Van’s startEngine(), Java callsCar’s definition • for Van’s move(), Java would call Van’s definition Object (all classes that you write are automatically subclasses of Java’s Object class) Car move startEngine Van move
Inheritance: Common Applications • What are some common applications of Inheritance in programming? • extending GUI (Graphical User Interface) components, such as buttons, sliders, pull-down menus to do things that are useful to your program • PushButton (class written by us) defines a release() method to do nothing (i.e. PushButton’s release() is an empty method) • PushButton is a general class that knows how to respond to being clicked on, an “event” • when user clicks onPushButton, its release() method is called automatically by Java’s “event dispatcher” • We could extend PushButton in order to redefine the release() method to do something useful! • like controlling a SportsCar or a CSMobile or a Van!
Let’s move some Cars (1 of 2) • public class VanButton extends PushButton { • private Van _van; • /** • * Not so clean to have button contain car, • * so we associate button with car in • * constructor. • */ • public VanButton(Van myVan) { • super( "Van" ); • _van = myVan; • } • public void release() { • _van.move(); • } • } // end of class VanButton • Typical constructor, except for "Van" • "Van" is called a string • stringsare words, phrases, or any other sequence of alphanumeric characters • more on strings later
Let’s move some Cars (2 of 2) public class SportsCarButton extends PushButton { private SportsCar _sportsCar; public SportsCarButton(SportsCar mySC) { super( "SportsCar" ); _sportsCar = mySC; } public void release() { _sportsCar.move(); } } // end of class SportsCarButton public class CSMobileButton extends PushButton { } // end of class CSMobileButton Can you fill this class O in?
Making the Program public class CarApp extends wheels.users.Frame { private Van _van; private VanButton _vanButton; private CSMobile _csMobile; private CSMobileButton _csMobileButton; private SportsCar _sportsCar; private SportsCarButton _sportsButton; public CarApp() { super(); _van = new Van(); _vanButton = new VanButton(_van); _csMobile = new CSMobile(); _csMobileButton = new CSMobileButton(_csMobile); _sportsCar = new SportsCar(); _sportsButton = new SportsCarButton(_sportsCar); // code to put buttons in different // locations on the screen } public static void main(String[] argv) { CarApp app = new CarApp(); } } // end of class CarApp remember to associate each button with the Car it’s expecting!