inheritance class hierarchies extending objects abstract methods abstract classes
DESCRIPTION
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? - PowerPoint PPT PresentationTRANSCRIPT
© 2006 Pearson EducationInheritance 1 of 31
INHERITANCE
• Class Hierarchies
• Extending Objects
• Abstract Methods
• Abstract Classes
• Overriding Methods
• protected
© 2006 Pearson EducationInheritance 2 of 31
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
© 2006 Pearson EducationInheritance 3 of 31
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
© 2006 Pearson EducationInheritance 4 of 31
• 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, and Moose “inherit from” Mammal
Inheritance
Animal
Reptile Mammal Fish
Cat Moose Dog
© 2006 Pearson EducationInheritance 5 of 31
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
Car
Van CSMobile SportsCar
© 2006 Pearson EducationInheritance 6 of 31
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., Mammal is 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)
© 2006 Pearson EducationInheritance 7 of 31
Inheriting Capabilities and Properties
• Subclass inherits all public capabilities of its superclass if Animals eat and sleep, then Reptiles, Mammals and Fish eat and sleep
if Cars move, then SportsCars move! anything superclass can do, subclass can do
• Subclass specializes its superclass by adding new methods, overriding existing
methods, and defining “abstract” methods declared 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?
© 2006 Pearson EducationInheritance 8 of 31
protected Instance 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!
© 2006 Pearson EducationInheritance 9 of 31
Inheritance Example
• Student inheritance 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.
Student
CollegeStudent
CSstudent
© 2006 Pearson EducationInheritance 10 of 31
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())
© 2006 Pearson EducationInheritance 11 of 31
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!
© 2006 Pearson EducationInheritance 12 of 31
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 abstract behavior and 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!
© 2006 Pearson EducationInheritance 13 of 31
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 no code 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”
© 2006 Pearson EducationInheritance 14 of 31
Abstract Methods, continued
• Reserved word abstract is modifier that says every subclass has specific capability, but superclass is unaware of implementation of 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 abstract method must itself be declared abstract
© 2006 Pearson EducationInheritance 15 of 31
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 abstract methods it can be instantiated it is concrete!
public abstract class Car {
// define to provide moving behavior
abstract public void move();
}
// This will not compile.
Car myCar = new Car();
note the semicolon!
© 2006 Pearson EducationInheritance 16 of 31
Code: Let’s make some Cars! (1 of 3)
public abstract class Car {
// properties of all Carsprivate 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
moveand startEngine?
© 2006 Pearson EducationInheritance 17 of 31
Code: Let’s make some Cars! (2 of 3)- Now that we are defining move(), it looks like any
other methodpublic 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…
© 2006 Pearson EducationInheritance 18 of 31
Code: Let’s make some Cars! (3 of 3)
public class SportsCar extends Car {
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
© 2006 Pearson EducationInheritance 19 of 31
Syntax: Declaring/Defining a Subclass
• To declare subclass of Car, we say that it extends superclass
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?
© 2006 Pearson EducationInheritance 20 of 31
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, Car is 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
© 2006 Pearson EducationInheritance 21 of 31
Syntax: superclass Constructors
• Use reserved word super to call superclass constructor it is as if superclass’ name is super 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();}
© 2006 Pearson EducationInheritance 22 of 31
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!
© 2006 Pearson EducationInheritance 23 of 31
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()
© 2006 Pearson EducationInheritance 24 of 31
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 startEngine replaces the one in superclass must be declared identically (in name and
parameter list!) — check documentation otherwise, nothing special about declaration
© 2006 Pearson EducationInheritance 25 of 31
How does Java call methods?
• We can use Van in 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 Van is created, its class
determines which methods will be called
© 2006 Pearson EducationInheritance 26 of 31
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 calls Car’s
definition for Van’s move(), Java would call Van’s
definition
Car
move startEngine
Van
move
Object
(all classes that you write are automatically subclasses of Java’s Object class)
© 2006 Pearson EducationInheritance 27 of 31
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 on PushButton, 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!
© 2006 Pearson EducationInheritance 28 of 31
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 strings are words, phrases, or any other
sequence of alphanumeric characters more on strings later
Let’s move some Cars (1 of 2)
© 2006 Pearson EducationInheritance 29 of 31
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?
© 2006 Pearson EducationInheritance 30 of 31
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!
© 2006 Pearson EducationInheritance 31 of 31