42
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff 1 15. 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

Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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

Page 2: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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

Page 3: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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.

Page 4: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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

Page 5: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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

Page 6: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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.

Page 7: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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.

Page 8: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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

Page 9: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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.

Page 10: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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

Page 11: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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?

Page 12: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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.

Page 13: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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

Page 14: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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

Page 15: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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;

}

}

Page 16: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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

Page 17: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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();

Page 18: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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

Page 19: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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?

Page 20: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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.

Page 21: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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?

Page 22: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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( )

Page 23: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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

Page 24: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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.

Page 25: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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) + “.”;} ...

}

Page 26: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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

Page 27: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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!

Page 28: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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);} ...

}

Page 29: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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.

Page 30: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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{

/******/

}

Page 31: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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

Page 32: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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;

}

Page 33: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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;

}

Page 34: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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?

Page 35: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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.

Page 36: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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

}

}

Page 37: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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!

Page 38: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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.

Page 39: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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();}

Page 40: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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(){…}

}

Page 41: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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);

Page 42: Outline 15. Inheritance 1courses.cs.vt.edu/~cs1054/notes/15.Inheritance.pdf · Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables:

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