L5

62
Object Object-Oriented Oriented Programming: Programming: Polymorphism Polymorphism Chapter 10 Chapter 10

description

nth

Transcript of L5

Page 1: L5

ObjectObject--Oriented Oriented

Programming: Programming:

PolymorphismPolymorphism

Chapter 10Chapter 10

Page 2: L5

22

What You Will LearnWhat You Will Learn

What is What is polypolymorphismmorphism??

How to declare and use How to declare and use virtualvirtual

functions for abstract classesfunctions for abstract classes

Page 3: L5

33

Problem with SubclassesProblem with Subclasses Given the class hierarchy below

Consider the existence of a draw function for each subclass

Consider also an array of references to the superclass (which can also point to various objects of the subclasses)

How do you specify which draw statement to be called when using the references

Shape class hierarchy

Circle

Right Triangle Isosceles Triangle

Triangle

Square

Rectangle

Shape

Page 4: L5

44

Introduction Introduction

PolymorphismPolymorphism

–– Enables “programming in the general”Enables “programming in the general”

–– The same invocation can produce “many The same invocation can produce “many forms” of resultsforms” of results

InterfacesInterfaces

–– Implemented by classes to assign common Implemented by classes to assign common functionality to possibly unrelated classes functionality to possibly unrelated classes

Page 5: L5

55

PolymorphismPolymorphism

When a program invokes a method When a program invokes a method through a superclass variable, through a superclass variable,

–– the correct subclass version of the method the correct subclass version of the method is called, is called,

–– based on the type of the reference stored based on the type of the reference stored in the superclass variablein the superclass variable

The same method name and signature The same method name and signature can cause different actions to occur, can cause different actions to occur,

–– depending on the type of object on which depending on the type of object on which the method is invokedthe method is invoked

Page 6: L5

66

PolymorphismPolymorphism

Polymorphism enables programmers to Polymorphism enables programmers to deal in generalities and deal in generalities and

–– let the executionlet the execution--time environment handle time environment handle the specifics. the specifics.

Programmers can command objects to Programmers can command objects to behave in manners appropriate to behave in manners appropriate to those objects, those objects,

––without knowing the types of the objects without knowing the types of the objects

–– (as long as the objects belong to the same (as long as the objects belong to the same inheritance hierarchy).inheritance hierarchy).

Page 7: L5

77

Polymorphism Promotes Polymorphism Promotes

ExtensibilityExtensibility

Software that invokes polymorphic Software that invokes polymorphic behaviorbehavior –– independent of the object types to which independent of the object types to which

messages are sent. messages are sent.

New object types that can respond to New object types that can respond to existing method calls can be existing method calls can be –– incorporated into a system without incorporated into a system without

requiring modification of the base system. requiring modification of the base system.

––Only client code that instantiates new Only client code that instantiates new objects must be modified to accommodate objects must be modified to accommodate new types.new types.

Page 8: L5

88

Demonstrating Polymorphic Demonstrating Polymorphic

Behavior Behavior

A superclass reference can be aimed at A superclass reference can be aimed at a subclass objecta subclass object

–– a subclass object “a subclass object “isis--a”a” superclass object superclass object

–– the type of the actual referenced the type of the actual referenced objectobject, , not the type of the not the type of the referencereference, determines , determines which method is calledwhich method is called

A subclass reference can be aimed at a A subclass reference can be aimed at a superclass object only if the object is superclass object only if the object is downcasteddowncasted

View example, View example, Figure 10.1Figure 10.1

Page 9: L5

99

PolymorphismPolymorphism

Promotes extensibilityPromotes extensibility

New objects types can respond to New objects types can respond to existing method callsexisting method calls

––Can be incorporated into a system without Can be incorporated into a system without modifying base systemmodifying base system

Only client code that instantiates the Only client code that instantiates the new objects must be modified new objects must be modified

––To accommodate new typesTo accommodate new types

Page 10: L5

1010

Abstract Classes and MethodsAbstract Classes and Methods

Abstract classes Abstract classes

––Are superclasses (called Are superclasses (called abstractabstract superclasses)superclasses)

––Cannot be instantiated Cannot be instantiated

–– IncompleteIncomplete

subclasses fill in "missing pieces"subclasses fill in "missing pieces"

Concrete classesConcrete classes

––Can be instantiatedCan be instantiated

–– Implement every method they declareImplement every method they declare

––Provide specificsProvide specifics

Page 11: L5

1111

Abstract Classes and Methods Abstract Classes and Methods

Purpose of an abstract classPurpose of an abstract class

––Declare common attributes …Declare common attributes …

––Declare common behaviors of classes in a Declare common behaviors of classes in a class hierarchyclass hierarchy

Contains one or more abstract Contains one or more abstract methodsmethods

––Subclasses must overrideSubclasses must override

Instance variables, concrete methods Instance variables, concrete methods of abstract classof abstract class

–– subject to normal rules of inheritancesubject to normal rules of inheritance

Page 12: L5

1212

Abstract ClassesAbstract Classes

Classes that are too general to Classes that are too general to create real objectscreate real objects

Used only as abstract superclasses Used only as abstract superclasses for concrete subclasses and to for concrete subclasses and to declare reference variablesdeclare reference variables

Many inheritance hierarchies have Many inheritance hierarchies have abstract superclasses occupying the abstract superclasses occupying the top few levelstop few levels

Page 13: L5

1313

Keyword Keyword abstractabstract

Use to declare a class Use to declare a class abstractabstract

Also use to declare a method Also use to declare a method abstractabstract

Abstract classes normally contain Abstract classes normally contain one or more abstract methodsone or more abstract methods

All concrete subclasses must All concrete subclasses must override all inherited abstract override all inherited abstract methodsmethods

Page 14: L5

1414

Abstract Classes and MethodsAbstract Classes and Methods

IteratorIterator classclass

–– Traverses all the objects in a Traverses all the objects in a collection, such as an arraycollection, such as an array

–– Often used in polymorphic Often used in polymorphic programming to traverse a collection programming to traverse a collection that contains references to objects that contains references to objects from various levels of a hierarchyfrom various levels of a hierarchy

Page 15: L5

1515

Abstract ClassesAbstract Classes

Declares common attributes and Declares common attributes and behaviors of the various classes in a behaviors of the various classes in a class hierarchy. class hierarchy.

Typically contains one or more abstract Typically contains one or more abstract methods methods

––Subclasses must override if the subclasses Subclasses must override if the subclasses are to be concrete. are to be concrete.

Instance variables and concrete Instance variables and concrete methods of an abstract class subject to methods of an abstract class subject to the normal rules of inheritance.the normal rules of inheritance.

Page 16: L5

1616

Beware! Compile Time ErrorsBeware! Compile Time Errors

Attempting to instantiate an object of Attempting to instantiate an object of an abstract class an abstract class

Failure to implement a superclass’s Failure to implement a superclass’s abstract methods in a subclass abstract methods in a subclass

––unless the subclass is also declared unless the subclass is also declared abstractabstract..

Page 17: L5

1717

Creating Abstract Superclass Creating Abstract Superclass EmployeeEmployee

abstractabstract superclass superclass Employee,Employee,

Figure 10.4Figure 10.4 –– earningsearnings is declared is declared abstractabstract

No implementation can be given for No implementation can be given for earningsearnings in the in the EmployeeEmployee abstractabstract classclass

–– An array of An array of EmployeeEmployee variables will store variables will store

references to subclass objectsreferences to subclass objects earningsearnings method calls from these variables method calls from these variables

will call the appropriate version of the will call the appropriate version of the earningsearnings methodmethod

Page 19: L5

1919

Polymorphic interface for the Polymorphic interface for the

EmployeeEmployee hierarchy classes.hierarchy classes.

Page 20: L5

2020

Note in Example HierarchyNote in Example Hierarchy

Dynamic bindingDynamic binding

––Also known as late bindingAlso known as late binding

––Calls to overridden methods are resolved Calls to overridden methods are resolved at execution time, based on the type of at execution time, based on the type of object referencedobject referenced

instanceofinstanceof operatoroperator

––Determines whether an object is an Determines whether an object is an instance of a certain typeinstance of a certain type

Page 21: L5

2121

How Do They Do That?How Do They Do That?

How does it work?How does it work?

––Access a derived object via base class Access a derived object via base class pointerpointer

–– Invoke an abstract methodInvoke an abstract method

––At run time the correct version of the At run time the correct version of the method is usedmethod is used

Design of the VDesign of the V--TableTable

––Note Note description from C++description from C++

Page 22: L5

2222

Note in Example HierarchyNote in Example Hierarchy

DowncastingDowncasting

––Convert a reference to a superclass to a Convert a reference to a superclass to a reference to a subclassreference to a subclass

––Allowed only if the object has an Allowed only if the object has an isis--aa relationship with the subclassrelationship with the subclass

getClassgetClass methodmethod

–– Inherited from Inherited from ObjectObject

––Returns an object of type Returns an object of type ClassClass

getNamegetName method of class method of class ClassClass

––Returns the class’s nameReturns the class’s name

Page 23: L5

2323

Superclass And Subclass Superclass And Subclass

Assignment RulesAssignment Rules

Assigning a superclass reference to Assigning a superclass reference to superclass variable straightforwardsuperclass variable straightforward

Subclass reference to subclass variable Subclass reference to subclass variable straightforwardstraightforward

Subclass reference to superclass variable Subclass reference to superclass variable safe safe –– because of because of isis--aa relationshiprelationship

–– Referring to subclassReferring to subclass--only members through only members through superclass variables a compilation errorsuperclass variables a compilation error

Superclass reference to a subclass variable a Superclass reference to a subclass variable a compilation errorcompilation error –– Downcasting can get around this errorDowncasting can get around this error

Page 24: L5

2424

finalfinal Methods and Classes Methods and Classes

finalfinal methodsmethods

–– Cannot be overridden in a subclassCannot be overridden in a subclass

–– privateprivate and and staticstatic methods implicitly methods implicitly finalfinal

–– finalfinal methods are resolved at compile methods are resolved at compile

time, this is known as static bindingtime, this is known as static binding

Compilers can optimize by inlining the codeCompilers can optimize by inlining the code

finalfinal classesclasses

–– Cannot be extended by a subclassCannot be extended by a subclass

–– All methods in a All methods in a finalfinal class implicitly class implicitly finalfinal

Page 25: L5

2525

Why Use InterfacesWhy Use Interfaces

Java has single inheritance, only Java has single inheritance, only

This means that a child class inherits This means that a child class inherits from only one parent class from only one parent class

Sometimes multiple inheritance would Sometimes multiple inheritance would be convenient be convenient

InterfacesInterfaces give Java some of the give Java some of the advantages of multiple inheritance advantages of multiple inheritance without incurring the disadvantages without incurring the disadvantages

Page 26: L5

2626

Why Use InterfacesWhy Use Interfaces

Provide capability for unrelated classes Provide capability for unrelated classes to implement a set of common to implement a set of common methodsmethods

Define and standardize ways people Define and standardize ways people and systems can interactand systems can interact

Interface specifies Interface specifies whatwhat operations operations must be permittedmust be permitted

Does Does notnot specify specify howhow performedperformed

Page 27: L5

2727

What is an Interface? What is an Interface?

An interface is a collection of constants An interface is a collection of constants and method declarations and method declarations

An interface describes a set of methods An interface describes a set of methods that can be called on an object that can be called on an object

The method declarations do not include The method declarations do not include an implementation an implementation

–– there is no method bodythere is no method body

Page 28: L5

2828

What is an Interface? What is an Interface?

A child class that A child class that extendsextends a parent a parent class can also class can also implementimplement an interface an interface to gain some additional behaviorto gain some additional behavior

Implementing an interface is a Implementing an interface is a “promise” to include the specified “promise” to include the specified method(s)method(s)

A method in an interface cannot be A method in an interface cannot be made made privateprivate

Page 29: L5

2929

When A Class Definition When A Class Definition

ImplementsImplements An Interface: An Interface:

It must implement each method in the It must implement each method in the interface interface

Each method must be Each method must be publicpublic (even (even though the interface might not say so) though the interface might not say so)

Constants from the interface can be Constants from the interface can be used as if they had been defined in the used as if they had been defined in the class (They should not be reclass (They should not be re--defined in defined in the class) the class)

Page 30: L5

3030

Declaring Constants with Interfaces Declaring Constants with Interfaces

Interfaces can be used to declare Interfaces can be used to declare constants used in many class constants used in many class declarationsdeclarations –– These constants are implicitly These constants are implicitly publicpublic, , staticstatic and and finalfinal

–– Using a Using a staticstatic importimport declaration allows declaration allows

clients to use these constants with just clients to use these constants with just their namestheir names

Page 31: L5

3131

Implementation vs. Interface Implementation vs. Interface

InheritanceInheritance

ImplementationImplementation InheritanceInheritance

Functionality high in the Functionality high in the hierarchyhierarchy

Each new subclass Each new subclass inherits one or more inherits one or more methods declared in methods declared in superclasssuperclass

Subclass uses Subclass uses superclass declarationssuperclass declarations

Interface InheritanceInterface Inheritance

Functionality lower in Functionality lower in hierarchyhierarchy

Superclass specifies one Superclass specifies one or more abstract or more abstract methodsmethods

Must be declared for Must be declared for each class in hierarchyeach class in hierarchy

Overridden for Overridden for subclasssubclass--specific specific implementationsimplementations

Page 32: L5

3232

Creating and Using InterfacesCreating and Using Interfaces

Declaration begins with Declaration begins with interfaceinterface

keywordkeyword

Classes Classes implementimplement an interface (and its an interface (and its

methods)methods)

Contains Contains publicpublic abstractabstract methodsmethods

––Classes (that Classes (that implementimplement the interface) the interface)

must implement these methodsmust implement these methods

Page 33: L5

3333

Creating and Using InterfacesCreating and Using Interfaces

Consider the possibility of having a Consider the possibility of having a class which manipulates mathematical class which manipulates mathematical functionsfunctions

You want to send You want to send a functiona function as a as a parameterparameter

––Note that C++ allows this directlyNote that C++ allows this directly

–– Java does notJava does not

This task can be accomplished with This task can be accomplished with interfacesinterfaces

Page 34: L5

3434

Creating and Using InterfacesCreating and Using Interfaces

Declare interface Declare interface FunctionFunction

Declare class Declare class MyFunctionMyFunction which which implements implements FunctionFunction

Note Note other functions other functions which are subclass which are subclass objectsobjects of of MyFunctionMyFunction

View View test program test program which passes which passes FunctionFunction subclass objects to function subclass objects to function

manipulation methodsmanipulation methods

Page 35: L5

3535

Case Study: A Case Study: A PayablePayable HierarchyHierarchy

PayablePayable interfaceinterface

––Contains method Contains method getPaymentAmountgetPaymentAmount

–– Is implemented by the Is implemented by the InvoiceInvoice and and EmployeeEmployee classesclasses

Click to view the test program

Page 36: L5

3636

End of Chapter 10 LectureEnd of Chapter 10 Lecture

Page 37: L5

3737

Following slides are from previous Following slides are from previous

edition. Links may not work.edition. Links may not work.

Page 38: L5

3838

Source Code for Source Code for ShapeShape Superclass Superclass

HierarchyHierarchy

Shape superclass, Shape superclass, Figure 10.6Figure 10.6 ––Note abstract method, Note abstract method, getNamegetName

Point subclass, Point subclass, Figure 10.7Figure 10.7 ––Note, extends Note, extends ShapeShape, override of , override of getNamegetName

Circle subclass, Circle subclass, Figure 10.8Figure 10.8 ––Note extends Note extends PointPoint, override of , override of getAreagetArea, , getNamegetName, and , and toStringtoString

Cylinder subclass, Cylinder subclass, Figure 10.9Figure 10.9 ––Note extends Circle, override of Note extends Circle, override of getAreagetArea, , getNamegetName, and , and toStringtoString

Page 39: L5

3939

Source Code for Source Code for ShapeShape Superclass Superclass

HierarchyHierarchy

Driver program to demonstrate, Driver program to demonstrate, Figure 10.10Figure 10.10

––Note array of superclass referencesNote array of superclass references

Output ofOutput of programprogram

Page 40: L5

4040

Polymorphic Payroll SystemPolymorphic Payroll System

Class hierarchy for polymorphic payroll applicationClass hierarchy for polymorphic payroll application

Employee

SalariedEmployee HourlyEmployee CommissionEmployee

BasePlusCommissionEmployee

Page 41: L5

4141

Polymorphic Payroll SystemPolymorphic Payroll System

Abstract superclass, Abstract superclass, EmployeeEmployee, , Figure 10.12Figure 10.12 ––Note abstract class specification, abstract Note abstract class specification, abstract earningsearnings method method

Abstract subclass, Abstract subclass, SalariedEmployeeSalariedEmployee, , Figure 10.13Figure 10.13 ––Note extends Note extends EmployeeEmployee, override of , override of earningsearnings methodmethod

Look at other subclasses in text, pg Look at other subclasses in text, pg 461 …461 … ––Note here also the override of Note here also the override of earningsearnings

Page 42: L5

4242

Polymorphic Payroll SystemPolymorphic Payroll System

View test program, View test program, Figure 10.17Figure 10.17

––Note array of superclass references which Note array of superclass references which are pointed at various subclass objectsare pointed at various subclass objects

––Note generic calls of Note generic calls of toStringtoString methodmethod

––Note use of Note use of instantceofinstantceof operatoroperator

––Consider use of downcasting (line 37)Consider use of downcasting (line 37)

––Note use of Note use of getClass().getName()getClass().getName()

methodmethod

Gives access to the name of the Gives access to the name of the classclass

Page 43: L5

4343

Polymorphic Payroll SystemPolymorphic Payroll System

Output of the Output of the payroll testingpayroll testing programprogram

Note results of Note results of getClass().getName()getClass().getName()

callscalls

Page 44: L5

4444

Creating and Using InterfacesCreating and Using Interfaces

View implementation of the interface View implementation of the interface Shape, Shape, Figure 10.19Figure 10.19 Note the following:Note the following:

–– Line 4Line 4 public class Point extends Object public class Point extends Object

implements Shape { …implements Shape { …

––Declaration of additional methodsDeclaration of additional methods

––Declaration of abstract methods Declaration of abstract methods getAreagetArea, , getVolumegetVolume, and , and getName getName

Page 45: L5

4545

Nested ClassesNested Classes

TopTop--level classeslevel classes

––Not declared inside a class or a methodNot declared inside a class or a method

Nested classesNested classes

––Declared inside other classesDeclared inside other classes

–– Inner classesInner classes

NonNon--static nested classesstatic nested classes

Demonstrated in Demonstrated in Figure 10.22Figure 10.22

––Run the programRun the program

––AudioAudio

Page 46: L5

4646

Mentioned In The AudioMentioned In The Audio

Inheritance Inheritance Hierarchy Hierarchy

Panes of a Panes of a JFrameJFrame

––BackgroundBackground

––ContentContent

––GlassGlass

Object

Component

Container

Window

Frame

JFrame

Page 47: L5

4747

Mentioned In The AudioMentioned In The Audio

Three things required when Three things required when performing eventsperforming events

1.1. Implement the interfaceImplement the interface

2.2. Register the event handlersRegister the event handlers

3.3. Specifically implement the Specifically implement the actionPerformedactionPerformed methodsmethods

Page 48: L5

4848

Nested ClassesNested Classes

An inner class is allowed to directly An inner class is allowed to directly access its inner class's variables and access its inner class's variables and methodsmethods

When When thisthis used in an inner classused in an inner class

––Refers to current innerRefers to current inner--class objectclass object

To access To access outerouter--class using class using thisthis

––Precede Precede thisthis with outerwith outer--class nameclass name

Page 49: L5

4949

Nested ClassesNested Classes

Anonymous inner classAnonymous inner class

––Declared inside a method of a classDeclared inside a method of a class

––Has no nameHas no name

Inner class declared inside a methodInner class declared inside a method

––Can access outer class's membersCan access outer class's members

–– Limited to local variables of method in Limited to local variables of method in which declaredwhich declared

Note use of anonymous inner class, Note use of anonymous inner class, Figure 10.23Figure 10.23

Page 50: L5

5050

Notes on Nested ClassesNotes on Nested Classes

Compiling class that contains nested classCompiling class that contains nested class

–– Results in separate Results in separate .class.class filefile

–– OuterClassName$InnerClassName.classOuterClassName$InnerClassName.class

Inner classes with names can be declared asInner classes with names can be declared as

–– publicpublic, , protectedprotected, , privateprivate or package accessor package access

Page 51: L5

5151

Notes on Nested ClassesNotes on Nested Classes

Access outer class’s Access outer class’s thisthis referencereference

OuterClassNameOuterClassName.this.this

Outer class is responsible for creating Outer class is responsible for creating inner class objectsinner class objects OuterClassName.InnerClassName innerRef = OuterClassName.InnerClassName innerRef =

ref.new InnerClassName();ref.new InnerClassName();

Nested classes can be declared Nested classes can be declared staticstatic

–– Object of outer class need not be createdObject of outer class need not be created

–– Static nested class does not have access Static nested class does not have access to outer class's nonto outer class's non--static membersstatic members

Page 52: L5

5252

TypeType--Wrapper Classes for Primitive Wrapper Classes for Primitive

TypesTypes

Each primitive type has oneEach primitive type has one

––Character, Byte, Integer, Character, Byte, Integer,

BooleanBoolean, etc., etc.

Enable to represent primitive as Enable to represent primitive as ObjectObject

––Primitive values can be processed Primitive values can be processed polymorphically using wrapper classespolymorphically using wrapper classes

Declared as Declared as finalfinal

Many methods are declared Many methods are declared staticstatic

Page 53: L5

5353

Invoking Superclass Methods from Invoking Superclass Methods from

Subclass ObjectsSubclass Objects

Recall the point and circle hierarchyRecall the point and circle hierarchy ––Note :Note :

Assignment of superclass reference to Assignment of superclass reference to superclass variablesuperclass variable

––Assignment of subclass reference to Assignment of subclass reference to subclass variablesubclass variable

No surprises … but the "isNo surprises … but the "is--a" a" relationship makes possiblerelationship makes possible ––Assignment of subclass reference to Assignment of subclass reference to

superclass variablesuperclass variable

See See Figure 10.1Figure 10.1

Page 54: L5

5454

Using Superclass References with Using Superclass References with

SubclassSubclass--Type VariablesType Variables

Suppose we have a superclass objectSuppose we have a superclass object Point3 point = new Point3 (30, 40);Point3 point = new Point3 (30, 40);

Then a subclass referenceThen a subclass reference Circle4 circle;Circle4 circle;

It would be illegal to have the subclass It would be illegal to have the subclass reference aimed at the superclass reference aimed at the superclass objectobject circle = point;circle = point;

Page 55: L5

5555

Subclass Method Calls via Subclass Method Calls via

SuperclassSuperclass--Type VariablesType Variables

Consider aiming a subclass Consider aiming a subclass reference at a superclass objectreference at a superclass object

–– If you use this to access a subclassIf you use this to access a subclass--only method it is illegalonly method it is illegal

Note Note Figure 10.3Figure 10.3

–– Lines 22 Lines 22 -- 2323

Page 56: L5

5656

Summary of Legal Assignments between Summary of Legal Assignments between

SuperSuper-- and Subclass Variablesand Subclass Variables

Assigning superclass reference to superclassAssigning superclass reference to superclass--type variable OKtype variable OK

Assigning subclass reference to subclassAssigning subclass reference to subclass--type variable OKtype variable OK

Assigning subclass object's reference to Assigning subclass object's reference to superclass typesuperclass type--variable, safevariable, safe –– A circle "is a" pointA circle "is a" point

–– Only possible to invoke superclass methodsOnly possible to invoke superclass methods

Do NOT assign superclass reference to Do NOT assign superclass reference to subclasssubclass--type variabletype variable –– You can cast the superclass reference to a You can cast the superclass reference to a

subclass type (explicitly)subclass type (explicitly)

Page 57: L5

5757

Polymorphism ExamplesPolymorphism Examples

Suppose designing video gameSuppose designing video game Superclass Superclass SpaceObjectSpaceObject

–– Subclasses Subclasses Martian, SpaceShip, LaserBeamMartian, SpaceShip, LaserBeam

–– Contains method Contains method drawdraw

To refresh screenTo refresh screen –– Send Send drawdraw message to each objectmessage to each object

–– Same message has “many forms” of resultsSame message has “many forms” of results

Easy to add class Easy to add class MercurianMercurian

–– Extends Extends SpaceObjectSpaceObject

–– Provides its own implementation of Provides its own implementation of drawdraw

Programmer does not need to change codeProgrammer does not need to change code –– Calls Calls drawdraw regardless of object’s typeregardless of object’s type –– MercurianMercurian objects “plug right in”objects “plug right in”

Page 58: L5

5858

PolymorphismPolymorphism

Enables programmers to deal in Enables programmers to deal in generalitiesgeneralities

–– Let executionLet execution--time environment handle time environment handle specificsspecifics

Able to command objects to behave in Able to command objects to behave in manners appropriate to those objectsmanners appropriate to those objects

––Don't need to know type of the objectDon't need to know type of the object

––Objects need only to belong to same Objects need only to belong to same inheritance hierarchyinheritance hierarchy

Page 59: L5

5959

Abstract Classes and MethodsAbstract Classes and Methods

Abstract classes not required, but Abstract classes not required, but reduce client code dependenciesreduce client code dependencies

To make a class abstractTo make a class abstract ––Declare with keyword Declare with keyword abstractabstract

––Contain one or more Contain one or more abstract methodsabstract methods public abstract void draw();public abstract void draw();

––Abstract methodsAbstract methods

No implementation, No implementation, mustmust be overriddenbe overridden

Page 60: L5

6060

Inheriting Interface and Inheriting Interface and

ImplementationImplementation

Make abstract superclass Make abstract superclass ShapeShape

Abstract method (must be implemented)Abstract method (must be implemented)

–– getNamegetName, , printprint

–– Default implementation does not make senseDefault implementation does not make sense

Methods may be overriddenMethods may be overridden

–– getAreagetArea, , getVolumegetVolume

Default implementations return Default implementations return 0.00.0

–– If not overridden, uses superclass default If not overridden, uses superclass default implementationimplementation

Subclasses Subclasses PointPoint, , CircleCircle, , CylinderCylinder

Page 61: L5

6161

Circle

Cylinder

Point

Shape

Polymorphic Interface For The

Shape Hierarchy Class

0.0

0.0

abstract

default Object

implement

0.0

0.0

"Point"

[x,y]

πr2

0.0

"Circle" center=[x,y];

radius=r

2πr2 +2πrh

πr2h

"Cylinder"

center=[x,y]; radius=r; height=h

getArea toString getName getVolume

Shape

Point

Circle

Cylinder

Page 62: L5

6262

Creating and Using InterfacesCreating and Using Interfaces

All the same "isAll the same "is--a" relationships apply a" relationships apply when an interface inheritance is usedwhen an interface inheritance is used

Objects of any class that extend the Objects of any class that extend the interface are also objects of the interface are also objects of the interface typeinterface type –– CircleCircle extends extends PointPoint, thus it is, thus it is--a a ShapeShape

Multiple interfaces are possibleMultiple interfaces are possible

––CommaComma--separated list used in declarationseparated list used in declaration