object-oriented programming: polymorphism chapter 10

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

Upload: rafe-mcgee

Post on 23-Dec-2015

234 views

Category:

Documents


0 download

TRANSCRIPT

Object-Oriented Object-Oriented Programming: Programming: PolymorphismPolymorphism

Chapter 10Chapter 10

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

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

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 resultsInterfacesInterfaces

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

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 variableThe 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

66

PolymorphismPolymorphism

Polymorphism enables programmers to Polymorphism enables programmers to deal in generalities and deal in generalities and – let the execution-time environment handle let the execution-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).

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.

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 “is-a”is-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

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

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

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

1212

  Abstract ClassesAbstract ClassesClasses 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

1313

Keyword Keyword abstractabstract

Use to declare a class Use to declare a class abstractabstractAlso 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

1414

  Abstract Classes and MethodsAbstract Classes and MethodsIteratorIterator class class

– Traverses all the objects in a collection, Traverses all the objects in a collection, such as an arraysuch 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

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.

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

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 class class

– An array of An array of EmployeeEmployee variables will store variables will store references to subclass objectsreferences to subclass objectsearningsearnings 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 method method

1818

Example Based on EmployeeExample Based on Employee

Abstract ClassAbstract Class

Concrete Classes

Concrete Classes

Click on Classes to see source codeClick on Classes to see source code

1919

Polymorphic interface for the Polymorphic interface for the EmployeeEmployee hierarchy classes. hierarchy classes.

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 operator operator– Determines whether an object is an Determines whether an object is an

instance of a certain typeinstance of a certain type

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 V-TableDesign of the V-Table

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

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 is-ais-a relationship with the subclassrelationship with the subclass

getClassgetClass method method– 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

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 is-ais-a relationship relationship– Referring to subclass-only members through Referring to subclass-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

2424

  finalfinal Methods and Classes Methods and Classes finalfinal methods methods

– 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 bindingCompilers can optimize by inlining the codeCompilers can optimize by inlining the code

finalfinal classes classes– 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

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

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 performed performed

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

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

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 re-defined in class (They should not be re-defined in the class) the class)

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

3131

Implementation vs. Interface Implementation vs. Interface InheritanceInheritance

ImplementationImplementationInheritanceInheritance

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 subclass-Overridden for subclass-specific specific implementationsimplementations

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 methods methods– Classes (that Classes (that implementimplement the interface) the interface)

must implement these methodsmust implement these methods

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

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

3535

Case Study: A Case Study: A PayablePayable Hierarchy Hierarchy

PayablePayable interface interface– Contains method Contains method getPaymentAmountgetPaymentAmount– Is implemented by the Is implemented by the InvoiceInvoice and and EmployeeEmployee classes classes

Click to view the test program

Click to view the test program

3636

End of Chapter 10 LectureEnd of Chapter 10 Lecture

3737

Following slides are from previous Following slides are from previous edition. Links may not work.edition. Links may not work.

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

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 ofprogramprogram

4040

Polymorphic Payroll SystemPolymorphic Payroll System

Class hierarchy for polymorphic payroll applicationClass hierarchy for polymorphic payroll application

Employee

SalariedEmployee HourlyEmployeeCommissionEmployee

BasePlusCommissionEmployee

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 method method

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

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 method method– Note use of Note use of instantceofinstantceof operator operator– Consider use of downcasting (line 37)Consider use of downcasting (line 37)– Note use of Note use of getClass().getName()getClass().getName()

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

4343

Polymorphic Payroll SystemPolymorphic Payroll System

Output of the Output of the payroll testingpayroll testingprogramprogram

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

4444

Creating and Using InterfacesCreating and Using Interfaces

View implementation of the interface View implementation of the interface Shape, Shape, Figure 10.19Figure 10.19Note the following:Note the following:– Line 4Line 4public 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

4545

Nested ClassesNested Classes

Top-level classesTop-level 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

Non-static nested classesNon-static nested classes

Demonstrated in Demonstrated in Figure 10.22Figure 10.22– Run the programRun the program– AudioAudio

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

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 methods methods

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 class used in an inner class– Refers to current inner-class objectRefers to current inner-class object

To access To access outerouter-class using -class using thisthis– Precede Precede thisthis with outer-class name with outer-class name

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

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 file file

– 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 access or package access

5151

Notes on Nested ClassesNotes on Nested Classes

Access outer class’s Access outer class’s thisthis reference referenceOuterClassNameOuterClassName.this.this

Outer class is responsible for creating Outer class is responsible for creating inner class objectsinner class objectsOuterClassName.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 non-static membersto outer class's non-static members

5252

Type-Wrapper Classes for Primitive Type-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

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 "is-a" No surprises … but the "is-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

5454

Using Superclass References with Using Superclass References with Subclass-Type VariablesSubclass-Type Variables

Suppose we have a superclass objectSuppose we have a superclass objectPoint3 point = new Point3 (30, Point3 point = new Point3 (30,

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

5555

Subclass Method Calls via Subclass Method Calls via Superclass-Type VariablesSuperclass-Type 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 subclass-If 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 - 23Lines 22 - 23

5656

Summary of Legal Assignments between Summary of Legal Assignments between Super- and Subclass VariablesSuper- and Subclass Variables

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

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

Assigning subclass object's reference to Assigning subclass object's reference to superclass type-variable, safesuperclass type-variable, 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 subclass-type variablesubclass-type variable– You can cast the superclass reference to a You can cast the superclass reference to a

subclass type (explicitly)subclass type (explicitly)

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 object message 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 type regardless of object’s type– MercurianMercurian objects “plug right in” objects “plug right in”

5858

PolymorphismPolymorphism

Enables programmers to deal in Enables programmers to deal in generalitiesgeneralities– Let execution-time environment handle Let execution-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

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 methodsNo implementation, No implementation, mustmust be overridden be overridden

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

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 toStringgetNamegetVolume

Shape

Point

Circle

Cylinder

6262

Creating and Using InterfacesCreating and Using Interfaces

All the same "is-a" relationships apply All the same "is-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-a , thus it is-a ShapeShape

Multiple interfaces are possibleMultiple interfaces are possible– Comma-separated list used in declarationComma-separated list used in declaration