55
013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

Embed Size (px)

Citation preview

Page 1: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Object-Oriented Programming: InheritanceCSE 1341

Page 2: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Abstraction

Page 3: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Abstraction

Page 4: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

BuildingBuilding

ChurchChurch ResidenceResidenceOfficeOffice SchoolSchool

CathedralCathedral

Page 5: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Die

A die component:• Has a face value. • Can roll itself — “Do It Myself.”

RegularDieRegularDie-faceValue: int-faceValue: int

+RegularDie()+getFaceValue(): int+setFaceValue(int):void+roll():int

+RegularDie()+getFaceValue(): int+setFaceValue(int):void+roll():int

Page 6: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Extending the Die Class

• Objects (software components) can have variations on a theme.

• Consider a new kind of Die, LoadedDie, that can remember a loaded side and set the value of half of the rolls to the loadedSide.

LoadedDieLoadedDie-faceValue: int-loadedSide: int-faceValue: int-loadedSide: int

+LoadedDie()+getFaceValue(): int+setFaceValue(int):void+getLoadedSide() : int+setLoadedSide(int):void+roll():int

+LoadedDie()+getFaceValue(): int+setFaceValue(int):void+getLoadedSide() : int+setLoadedSide(int):void+roll():int

Page 7: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Die and LoadedDie: Common Parts

LoadedDieLoadedDie-faceValue: int-loadedSide: int

+LoadedDie()+getFaceValue(): int+setFaceValue(int):void+getLoadedSide() : int+setLoadedSide(int):void+roll():int

RegularDieRegularDie-faceValue: int-faceValue: int

+RegularDie()+getFaceValue(): int+setFaceValue(int):void+roll():int

+RegularDie()+getFaceValue(): int+setFaceValue(int):void+roll():int

Page 8: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Inheritance

LoadedDieLoadedDie-loadedSide: int

+LoadedDie()+getLoadedSide() : int+setLoadedSide(int):void+roll() : int

RegularDieRegularDie-faceValue: int-faceValue: int

+RegularDie()+getFaceValue(): int+setFaceValue(int):void+roll():int

+RegularDie()+getFaceValue(): int+setFaceValue(int):void+roll():int

over-riddenover-ridden

inheritedinheritedinheritedinherited

addedaddedaddedaddedaddedadded

inheritedinherited SuperclassSuperclass

SubclassSubclass

Page 9: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Inheritance

LoadedDieLoadedDie-loadedSide: int

+LoadedDie()+getLoadedSide() : int+setLoadedSide(int):void+roll() : int

RegularDieRegularDie-faceValue: int-faceValue: int

+Die()+getFaceValue(): int+setFaceValue(int):void+roll():int

+Die()+getFaceValue(): int+setFaceValue(int):void+roll():int

• Inheritance:– Is present when software

classes are organized in a generalization-specialization hierarchy.

– Means that a subclass acquires all of the attribute and method definitions of its superclass.

• A subclass can add its own unique attributes and behaviors.

• A subclass might also override (redefine) an inherited method.

• Advantages?

over-riddenover-ridden

inheritedinheritedinheritedinherited

addedaddedaddedaddedaddedadded

inheritedinherited

Page 10: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Polymorphism• Polymorphism means:

– The same message can be interpreted in different ways, depending on the receiver.

– A method by the same name can be defined in different classes.

• How do you know which method will be executed when you send a message?

• Advantages?

roll()

roll()

RegularDieRegularDie

LoadedDieLoadedDie

Page 11: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

LoadedDieLoadedDie-loadedSide: int

+LoadedDie()+getLoadedSide() : int+setLoadedSide(int):void+roll() : int

TenSidedDieTenSidedDie

+TenSidedDie()+roll() : int+TenSidedDie()+roll() : int

DieDie-faceValue: int-faceValue: int

+Die()+getFaceValue(): int+setFaceValue(int):void+roll():int

+Die()+getFaceValue(): int+setFaceValue(int):void+roll():int

Abstract Superclass

•Not instantiated.•Superclass exists only to define common parts.

Abstract Superclass

•Not instantiated.•Superclass exists only to define common parts.

RegularDieRegularDie

+RegularDie()+RegularDie()

Page 12: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

DieDie

LoadedDieLoadedDieRegularDieRegularDie

TenSidedDieTenSidedDie

Page 13: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Abstract and Concrete Classes

Abstract class:• Not instantiated.• Superclass to define

common parts.

LoadedDie

loadedSide

roll()setLoadedSide()

Die

faceValue

getFaceValue()

abstract superclass

concreteclasses

RegularDie

roll()

YahtzeeDie

roll()

Concrete class:Instantiated.

Page 14: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Domain Modeling: Inheritance

• Generalizations should be discovered, not predicted.– In analysis, observe common relationships and common attributes.– In design, observe shared behavior for which delegation cannot be

used to provide the common implementation.

• 100% Rule: All statements about the generalization are valid for the specialization.

• IF you keep Superclasses abstract, they’ll be more stable.

Page 15: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

DieDie

LoadedDieLoadedDie

rollrollRegularDieRegularDie

Page 16: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Is a…AnimalAnimal

CatCat

DogDog“Bark”“Bark”

“”“”

“Meow”“Meow”

talktalk

Page 17: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

?talktalk

Page 18: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

public abstract class Animal{ public abstract String talk();}

public class Dog extends Animal{ public String talk() {

return “Yip!”; }

}

Page 19: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

If I throw objects into a bag…

Page 20: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Domain Modeling: Inheritance

Order #: StringTracking #: StringShipping Address: PostalAddressTaxes: : MoneyS&H Charge: Money/Total: Money

Order

1 0..1Paid by

UserNameTransactionIdTimestamp

PayPalPayment

Amount Paid

Payment

CreditCardPayment

NameCard NumberExpiration DateBilling Address: PostalAddress

Credit Card

Approval

Credit Charge Request

11

uses

0..1

1

Authorized by

Page 21: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Polymorphism

One request handled by receiver in different ways.- the requestor doesn’t have to get involved in details- the receiver does what it best knows how to do

Page 22: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Traditional handling approach withconditional logic:

public Money getTotalPrice() {Money price;

// calculate prices and tax…

if (shipping.equals("Standard")) {price += //calculate standard

shipping} else if (shipping.equals("Ground")) {

price += //calculate ground shipping} else if (shipping.equals("Priority")) {

price += //calculate ground shipping} // FIXME: support Int’l Shipping!

return price; }

Page 23: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

public Date getEstimatedDeliveryDate() {Date dueDate;

if (shipping.equals("Standard")) { dueDate = //calculate standard

shipping} else if (shipping.equals("Ground")) {

dueDate = //calculate ground shipping

} else if (shipping.equals("Priority")) { dueDate = //calculate ground

shipping} // FIXME: support Courier

return dueDate; }

Page 24: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

What now?

Page 25: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Better? public Money getTotalPrice() {

Money price;// calculate prices and tax…price +=

shippingStrategy.getShippingCost(weight,

dimensions,

destination);return price;

}

public Date getEstimatedDeliveryDate() {Date dueDate =

shippingStrategy.getEstimatedDeliveryDate(); return dueDate;

}

Page 26: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Polymorphism Example

getEstimatedDeliveryDate()getShippingCost()

<<abstract>>ShippingStrategy

getEstimatedDeliveryDate()getShippingCost()

StandardShippingStrategy

getEstimatedDeliveryDate()getShippingCost()

GroundShippingStrategy

getEstimatedDeliveryDate()getShippingCost()

PriorityShippingStrategy

Page 27: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Basic Inheritance Terminology

• Superclass• Subclass• Specialization• Inheritance• Class Hierarchy• “Is a” (vs. “Has a”)

Page 28: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

More Terminology

• The direct superclass is the superclass from which the subclass explicitly inherits.

• An indirect superclass is any class above the direct superclass in the class hierarchy.

• The Java class hierarchy begins with class Object (in package java.lang) Every class in Java directly or indirectly extends (or

“inherits from”) Object.

• Java supports only single inheritance, in which each class is derived from exactly one direct superclass.

Page 29: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

SlotSlot

-amount : int-amount : int

+getScore():int+getScore():int

SpinGameSpinGame

+SpinGame()+playGame():void+displayScore():void

+SpinGame()+playGame():void+displayScore():void

101

GameTesterGameTester

+main(String[]):void+main(String[]):void

slots

1 1

game

WheelWheel

+Wheel()+spin():int+Wheel()+spin():int

theWheel

11

LoseSlotLoseSlot

+getScore():int+getScore():int

WinSlotWinSlot

+getScore():int+getScore():int

BonusSlotBonusSlot

+getScore():int+getScore():int

Page 30: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Page 31: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

protected Members

• A class’s public members are accessible wherever the program has a reference to an object of that class or one of its subclasses.

• A class’s private members are accessible only within the class itself.

• protected access is an intermediate level of access between public and private. A superclass’s protected members can be accessed by members

of that superclass, by members of its subclasses and by members of other classes in the same package

• protected members also have package access. All public and protected superclass members retain their original

access modifier when they become members of the subclass.

Page 32: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

protected Members (Cont.)

• A superclass’s private members are hidden in its subclasses They can be accessed only through the public or protected

methods inherited from the superclass

• Subclass methods can refer to public and protected members inherited from the superclass simply by using the member names.

• When a subclass method overrides an inherited superclass method, the superclass method can be accessed from the subclass by preceding the superclass method name with keyword super and a dot (.) separator.

Page 33: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Use of private with Inheritance

• Members of a subclass cannot access private members of its superclass.

• Preferred: Access the superclass attributes through methods in the superclass.

• Alternative: Declare superclass attributes as protected.

Page 34: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

StudentStudent

-studentNumber: int

+Student()+Student(String,int)+getStudentNumber() : int+setStudentNumber(int):void+equalsl(Student) : boolean+toString() : String

PersonPerson

-name : String-name : String

+Person()+Person(String)+getName(): String+setName(String):void+sameName(Person):boolean+toString():String

+Person()+Person(String)+getName(): String+setName(String):void+sameName(Person):boolean+toString():String

Another Example:

Page 35: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

public class Person{ private String name;

public Person() { name = "No name yet."; } public Person(String initialName) { name = initialName; } public void setName(String newName) { name = newName; }

Example: BaseClassBaseClass

public String getName() { return name; }

public toString () { return ”Person: " + name; }

public boolean sameName(Person otherPerson) { return (this.name.equalsIgnoreCase(otherPerson.name)); }

}

Page 36: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Programming Example:

DerivedClass

DerivedClass

public class Student extends Person{ private int studentNumber; public Student() { super();//super is explained in a later section. studentNumber = 0;//Indicating no number yet } public Student(String initialName, int initialStudentNumber) { super(initialName); studentNumber = initialStudentNumber; }

public int getStudentNumber() { return studentNumber; } public void setStudentNumber(int newStudentNumber) { studentNumber = newStudentNumber; }

public String toStringt() { return super.toString() + ” Student Number : " + studentNumber; }

public boolean equals(Student otherStudent) { return (this.sameName(otherStudent) && (this.studentNumber == otherStudent.studentNumber)); }}

Page 37: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Programming Example:

TestClassTestClass

public class InheritanceDemo{ public static void main(String[] args) { Student s = new Student(); s.setName("Warren Peace"); //setName is inherited from the class Person.

s.setStudentNumber(2001); s.writeOutput(); }}

Screen Output

Name: Warren PeaceStudent Number: 2001

Page 38: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Review…

• Private attributes cannot be accessed in subclass

• Private methods are not inherited

• Overloading: same method name, different parameters

• Overriding: same method signature implemented in a subclass

Page 39: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Also...

• Constructors are not inherited.

• The first task of a subclass constructor is to call its direct superclass’s constructor explicitly or implicitly Ensures that the instance variables inherited from the

superclass are initialized properly.

• If the code does not include an explicit call to the superclass constructor, Java implicitly calls the superclass’s default or no-argument constructor.

• A class’s default constructor calls the superclass’s default or no-argument constructor.

Page 40: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Inheriting from “Object”

• toString is one of the methods that every class inherits directly or indirectly from class Object. Returns a String representing an object. Called implicitly whenever an object must be converted to

a String representation.

• Class Object’s toString method returns a String that includes the name of the object’s class. This is primarily a placeholder that can be overridden by a

subclass to specify an appropriate String representation.

Page 41: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Page 42: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

protected members

• Using protected instance variables creates several potential problems.

• The subclass object can set an inherited variable’s value directly without using a set method. A subclass object can assign an invalid value to the

variable, possibly leaving the object in an inconsistent state.

• Subclass methods are more likely to be written so that they depend on the superclass’s data implementation. Subclasses should depend only on the superclass services

and not on the superclass data implementation.

Page 43: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Page 44: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University (C) 2010 Pearson Education, Inc. All rights

reserved.

Page 45: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Page 46: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Page 47: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Page 48: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Page 49: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Page 50: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Page 51: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

public void foo(){ foo(); doSomething(); doSomethingElse();}

public void foo(){ super.foo(); doSomething(); doSomethingElse();}

VS.

Page 52: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

9.6  Constructors in Subclasses

• Instantiating a subclass object begins a chain of constructor calls The subclass constructor, before performing its own tasks, invokes

its direct superclass’s constructor

• If the superclass is derived from another class, the superclass constructor invokes the constructor of the next class up the hierarchy, and so on.

• The last constructor called in the chain is always class Object’s constructor.

• Original subclass constructor’s body finishes executing last. • Each superclass’s constructor manipulates the superclass

instance variables that the subclass object inherits.

Page 53: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Page 54: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Software Engineering with Inheritance

• When you extend a class, the new class inherits the superclass’s members—though the private superclass members are hidden in the new class.

• You can customize the new class to meet your needs by including additional members and by overriding superclass members. Doing this does not require the subclass programmer to

change (or even have access to) the superclass’s source code.

Java simply requires access to the superclass’s .class file.

Page 55: © 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University

Object Class• All classes in Java inherit directly or indirectly from Object, so

its 11 methods are inherited by all other classes. • Figure 9.12 summarizes Object’s methods. • Can learn more about Object’s methods in the online API

documentation and in The Java Tutorial at :java.sun.com/javase-/6/docs/api/java/lang/Object.html

orjava.sun.com/docs/books/tutorial/java/IandI/ objectclass.html

• Every array has an overridden clone method that copies the array. If the array stores references to objects, the objects are not copied—a

shallow copy is performed. • For more information about the relationship between arrays and

class Object, see Java Language Specification, Chapter 10, at java.sun.com/docs/books/jls/third_edition/ html/arrays.html