outline 15. inheritance 1courses.cs.vt.edu/~cs1054/notes/15.inheritance.pdf · inheritance: extends...
TRANSCRIPT
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
115. Inheritance
Programming in Java
Outline
■ Inheritance: extends ; Superclasses and Subclasses■ Valid and invalid object states, & Instance variables:
protected
■ Inheritance and constructors, super■ The “is-a” vs. “has-a” relationship
(Inheritance vs. Composition)■ Class hierarchies & the Object class■ Overriding vs. Overloading■ Polymorphism■ Factoring out Common Behavior■ Abstract methods and classes■ Interfaces: implements
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
215. Inheritance
Programming in Java
Inheritance
■ In real life, “hierarchies” of classes exist.
■ myCar is just as easily a member of the Ford class as the Automobile class
radioShackmyCarobject
CorporateCustomerFordClass
CustomerAutomobileClass
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
315. Inheritance
Programming in Java
Inheritance: extends
■ This relationship is supported in Java by inheritance.– made possible by the extends keyword.
class Ford extends Automobile{
... ... ...
}
– Original class (Automobile) is the Base class.– Newly defined class (Ford) is the Derived class.– Base class must exist to make a Derived class.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
415. Inheritance
Programming in Java
Inheritance
■ Derived classes inherit all data from the Base class.■ Derived classes inherit all the method interfaces from the Base class, but may
specify a new implementation. ■ Derived classes may also add new methods.■ The Base class is referred to as super
– Base class = superclass; Derived class = subclass
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
515. Inheritance
Programming in Java
Inheritance: BetterBR Example.1
■ BetterBR– Want to create a BufferedReader from a file name without having to
worry about code for the InputStreamReader, FileInputStream, and File classes.
– Want to be able to read an int as easily as we read a String.– The user-defined BetterBR class extends the Java BufferedReader class– BetterBR objects are also BufferedReader objects– BetterBR objects can be used the same as BufferedReader objects
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
615. Inheritance
Programming in Java
Inheritance : BetterBR Example.2
class BetterBR extends BufferedReader{
public BetterBR(String filename) throws IOException{
super(new InputStreamReader(
new FileInputStream(
new File(filename))));
}
public BetterBR() throws IOException {
super(new InputStreamReader(System.in));
}
. . . . . . . . . . . . .
super invokes the base class constructor.
If a derived class has additional data members then their initialization should take place after the invocation of the super constructor.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
715. Inheritance
Programming in Java
Inheritance : BetterBR Example.3
. . . . . . . . . . . . .
public int readInt() throws Exception {
string line;
line = readLine();
return Integer.parseInt(line);
}
}
Why can we do this?
readInt() is a BetterBR method, but not a BufferedReader method.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
815. Inheritance
Programming in Java
Inheritance : BetterBR Example.4
main (String[] arg) throws Exception{
int i;
String s;
BetterBR bbr = new BetterBR(“junk.txt”);
i = bbr.readint();
while ( i >= 0) {
System.out.println(“i = “ + i);
i = bbr.readint();
}
s = bbr.readLine();
while ( s != null ) {
System.out.println(“s = “ + s);
s = bbr.readLine();
}
}
35237-1A lineLine #2Last line
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
915. Inheritance
Programming in Java
Object States
■ A Derived class inherits, (takes on), the data members (instancevariables) of the Base class.
■ The data members define an object’s state.■ A derived class may include (extend) additional data (and
function) members.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1015. Inheritance
Programming in Java
class Name {
private String firstName, lastName, title;
public Name(String first, String last){
firstName = first; lastname = last;title = “ ”;
}
} // ================================================
class ExtendedName extends Name{
private String middleName;
public ExtendedName(String firstName, StringmiddleName, String lastName){
super(firstName, lastName);
this.middleName = middleName;
}
}
What does this do??
How doesExtendedName’sconstructor ensurea valid state forName ?
Object States: ExtendedName Eg.1
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1115. Inheritance
Programming in Java
Object States : ExtendedName Eg.2
■ A two-parameter constructor:
public ExtendedName(String firstName, String lastName) {
super(firstName, lastName);
middleName = “”;// this.middleName = “”;
}
How does thisconstructor ensure
a valid state?
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1215. Inheritance
Programming in Java
Object States : ExtendedName Eg.3
■ A derived class’s methods should never put the base class in an invalid state.– A valid state is:
■ Meaningful in the base class■ Possible in the base class
■ Invalid state
public ExtendedName(String firstName, String middleName,
String lastName){
super(“”, “”);
middleName = “”;
}
■ The above code would place the inherited base class instance variables in an invalid state because the base class constructors never specified empty string states.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1315. Inheritance
Programming in Java
Object States & Access
■ Inherited class may need to directly access the private instance variables in the base class!
– Private members of the base class may not be directly accessed by derived classes.
– How can you protect your original class from being corrupted by client code, but still allow derived class code to access/modify base class instance variables?
– Accessor and mutator methods could be provided, but they may be inappropriate for client code invocation.
– Some data members should be able to be changed by derived class code, but not by client class code?
– Solution: protected keyword
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1415. Inheritance
Programming in Java
Object Access
■ Three ways to classify accessibility of class members: private , public , protected
■ Protected members in the Base class are private in the Derived class■ Private members in the Base class are inaccessible in the Derived class, even
to the methods of the Derived class.■ Public members in the Base class are public in the Derived class
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1515. Inheritance
Programming in Java
Object statesclass Name {
protected String firstName, lastName, title;
public Name(String first, String last){
firstName = first; lastname = last;
}
}
// ================================================
class ExtendedName extends Name {
private String middleName;
public ExtendedName(String firstName, StringmiddleName, String lastName){
super(firstName, lastName);title = “ ”; //base member access
this.middleName = middleName;
}
}
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1615. Inheritance
Programming in Java
Object states
■ Which should you use in a base class?– private , public , protected
■ Some people think all base class data should be private– Then the derived class can’t possibly invalidate the base class!
■ Others think all base class data should be protected– Makes it easy to do what you want with the derived class
■ Comparison:
Works like public
Works like public
public
inaccessibleWorks like private
private
Works like private
Works like public
protected
In derivedIn base
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1715. Inheritance
Programming in Java
Constructors
middleName
firstNamelastName
title
■ When a derived class’s constructor is called:– Room is reserved for all the data members of both the derived class and its
base class – in the same object.– The base class data gets set up…– then the derived class data gets set up.
– Derived class constructor mustpass needed info to the baseclass constructor: super();
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1815. Inheritance
Programming in Java
“is-a” vs. “has-a”
■ “Is-a”– An object of a derived class
is an object of the base class– In the left picture,
a is a
• “Has-a”– This is how we’ve programmed
up until now.– In the right picture,
a has a
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1915. Inheritance
Programming in Java
“is-a” vs. “has-a”
■ The “is-a” relationship is calledinheritance
■ The “has-a” relationship is calledcomposition (aggregation)
class Name2 {public Name2( String firstName,
String middleName,String lastName ){...}
private Name n;
private String middleName;
}
What are some disadvantages to composition?
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2015. Inheritance
Programming in Java
When to use Inheritance
■ If all methods of the original class X should be methods of the new class Y, then use inheritance.
■ If some of the methods of the original class X should be methods of the new class Y, then use composition.
■ If it feels right to say that “a Y is an X” (as in “a part-timer is an employee”), then use inheritance.
■ If it feels right to say that “a Y has an X” (as in “an employee has a name”), then use composition.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2115. Inheritance
Programming in Java
Don’t make this mistake:
class Name {
public String firstName, lastName;
public Name (String f, String l){...};
}
/***********************************************/
class ExtendedName extends Name {
public String firstName, lastName, middleName;
public ExtendedName (String f,String m,
String l){...};
}
What’s wrong here?
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2215. Inheritance
Programming in Java
The Object class
■ We’ve used the Object class many times.– Vectors store only type object.
■ An Object is the very first, basic class defined by Java.■ Every class implicitly inherits from the Object class (either directly or
indirectly).– It has some specific methods you can
re-define (or override). Some are:boolean equals(Object other)String toString( )
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2315. Inheritance
Programming in Java
Class hierarchies in Java
■ Both of these are possible:– Title could be moved from the base Name class
since not all names have a title. Name
Name ExtendedName
ExtendedName SuffixedNameSuffixedName
Two subclasses for 1 superclassSubclasses extended toanother subclass
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2415. Inheritance
Programming in Java
Overriding
■ When a method is defined in a base class, it may be overridden (redefined differently) in the derived class.Technique:
– 1) override a method in a derived class, (i.e. provide an implementation of a base class function in the derived class)
– 2) create an object of the derived type– 3) invoke the overridden method
■ Whether the object is cast as the base type or derived type, the derived method’s implementation is used.
■ Don’t confuse this with overloading■ Overloading: writing 2 methods in one class with the same name,
differing by parameter lists.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2515. Inheritance
Programming in Java
Overriding
class Name{
public String getInitials(){
return fName.substring(0,1) + “.” +
lName.subString(0,1) + “.”;} ...
}
/***********************************************/
class ExtendedName extends Name{
public String getInitials(){
return fName.substring(0,1) + “.” +getMiddleInitial() + “.” +
lName.subString(0,1) + “.”;} ...
}
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2615. Inheritance
Programming in Java
Definition: Polymorphism
■ Polymorphism, in programming, is the ability to write code that is independent of the exact type of objects upon which it is executing.
■ Polymorphic code is general code that only relies upon the common properties of objects in an inheritance hierarchy.
■ General polymorphic code treats all objects of an inheritance hierarchy as base class objects.
■ Polymorphism depends on inheritance and overriding.■ An object of the subclass can be referred to as an object of the superclass.■ When an overridden method is invoked upon an object reference of the
superclass, the body of the subclass’s overridden method is executed, (not the base class’ implementation).
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2715. Inheritance
Programming in Java
Polymorphism: simple example
Vector v;
Name n = new Name(“Bill”, “Clinton”);
v.add(n);
ExtendedName en = new ExtendedName(“George”, “W”, “Bush”);
v.add(en);
/**********************************************/
for(int I=0; I < v.size(); I++){
String s = ( (Name) v.elementAt(I) ).getInitials();
System.out.println(s);
} B.C.G.W.B.
At this point, wedon’t know (orcare) what kind ofName is beingreferenced!
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2815. Inheritance
Programming in Java
Overriden Base Member Invocation
■ A derived class over-riding function may invoke the base class version by use of the super keywordclass Name{
public void print(){
system.out.print( lastName + “, ” + firstName);} ...
}
/***********************************************/
class ExtendedName extends Name{
public void print(){
super.print(); //invoke base class version
system.out.print( “, ” + middleName);} ...
}
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2915. Inheritance
Programming in Java
Do you understand?
■ Explain the difference between overloading and overriding■ Explain the difference between inheritance and polymorphism■ Explain the difference between base and derived■ What 3 things must we have in order for these concepts to be useful?■ Where is the Object class in the Java hierarchy?■ Why would you want to do any of this?
Give examples.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
3015. Inheritance
Programming in Java
Applets
■ Applet classes inherit from the Applet class■ Powerful set of GUI tools / window management.
class myWebProgram extends Applet{
/******/
}
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
3115. Inheritance
Programming in Java
Factoring out Common Behavior
■ When designing a set of classes with some commonality, look for their common behavior
■ Example: camera store sells:– Lenses – focal length, zoom capability (Boolean)– Film – storage temperature, # exposures– Cameras – w/lens(bool), shutter speed, body color
■ ... But all of them have:– Description, quantity on hand, price, inventory number
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
3215. Inheritance
Programming in Java
Factoring out Common Behavior
class InventoryItem{
InventoryItem(…){…} // constructor
String getDescription(){return desc;}
int getQuantityOnHand(){return qOH;}
int getPrice(){return price;}
String desc; // description
int inventoryNumber;
int qOH; // quantity on hand
int price;
}
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
3315. Inheritance
Programming in Java
Factoring out Common Behavior
class Lens extends InventoryItem{
Lens(…){ // constructor
super(…);
/* other code */
}
/* METHODS SPECIFIC TO LENS*/
boolean isZoom(){return zoom;}
double getFocalLength(){return focalLength};
/* INSTANCE VARIABLES SPECIFIC TO LENS*/
boolean zoom;
double focalLength;
}
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
3415. Inheritance
Programming in Java
Abstract methods & classes
■ A base class doesn’t have to define all its methods! It can simply provide a prototype.
■ If any method in a class doesn’t have an implementation, it is an abstract method.
■ Any class with an abstract method is an abstract class.■ An abstract class cannot be instantiated.
(You cannot create an object of that type.)– Why are abstract classes useful then?
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
3515. Inheritance
Programming in Java
Abstract methods & classes
■ Suppose you want to print out your camera store inventory items.– All items will be stored in the same vector, so when you getNextElement(),
you won’t know whether you have a lens, camera, or film.■ You could provide a method in InventoryItem called print() , and then
override it in all subclasses…– But what would the body of
InventoryItem.print() look like?– You can’t define it, because the info you print depends on the type of item.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
3615. Inheritance
Programming in Java
Abstract methods & classes
abstract class InventoryItem{
public InventoryItem(){…} // etc.
abstract public void print(); // no body!
// other stuff
}
/**********************************/
class Lens extends InventoryItem{
void public print(){
if (zoom)
System.out.printLn(“Zoom”);
System.out.println(“Lens ”);
// other stuff
}
}
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
3715. Inheritance
Programming in Java
Abstract classes
■ Another example is the InputStream class.– InputStream is abstract. You cannot instantiate it directly.– But there are several derived classes which you can instantiate.
■ StringBufferInputStream, FileInputStream, and FilterInputStream…– InputStreamReader’s constructor requires an InputStream argument.– We can give InputStreamReader an object from any derived class. – Each derived class works differently, but InputStreamReader never needs to
know what type of InputStream it has!
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
3815. Inheritance
Programming in Java
Interfaces
■ Sometimes you need to specify generic behavior for a group of classes that are not related in any obvious hierarchical way.
■ Example: the Enumeration type.– Suppose you add another inventory item to your camera store: a “package
deal”, including a camera, several lenses, and several rolls of film.– Your class must inherit from your InventoryItem class, for obvious reasons.– But let’s say you also want it to work as an Enumeration type – spitting out
one of the packaged items at a time.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
3915. Inheritance
Programming in Java
Interfaces
■ Fortunately, Enumeration is not a class…– …it’s an interface.– It has no method bodies, just prototypes.– It is not a class.
interface Enumeration{
Object nextElement();
boolean hasMoreElements();}
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
4015. Inheritance
Programming in Java
The implements keyword
class PackageDeal extends InventoryItem
implements Enumeration{
private Vector packagedItems;
public PackageDeal(…){…}
// etc...
Object nextElement(){…}
boolean hasMoreElements(){…}
}
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
4115. Inheritance
Programming in Java
The implements keyword
■ Now, if you had a method that took an Enumeration and wrote out the contents…
myUtils.writeEnum(e, System.out);
– You could pass it your PackageDeal objects and it would do the same thing.myUtils.writeEnum(myPD, System.out);
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
4215. Inheritance
Programming in Java
The implements keyword
class myUtils{public static void writeEnum(Enumeration e,
PrintStream output){String s;while ( e.hasMoreElements() ){
s = e.nextElement().toString();output.println(s);
}}
}toString() inheritedfrom Object class