polymorphism - ocw.udl.cat
TRANSCRIPT
Polymorphism
Josep Maria Ribo
February, 2010
J.M.Ribo ([email protected]) Polymorphism February, 2010 1 / 27
ndex
1 Types and classesTypesClasses
2 Notion of polymorphism
3 Abstract classes and interfacesAbstract classesInterfacesAbstract classes vs. Interfaces
4 Conversion and type checking
5 Reflection
J.M.Ribo ([email protected]) Polymorphism February, 2010 2 / 27
Types and classes Types
Types
Type
A type characterizes a collection of objects or values in terms of theirbehaviour.This behaviour is modelled in terms of operations that can be performedon those objects/values.
Examples of types:int, float, char, String, Student, Comparable, Readable,MediaPlayer...
Operations associated to int: +,-,*, /, %
Operations associated to Student: setName(), getName(),enrolToSubject(), getEnrolledSubjects()
J.M.Ribo ([email protected]) Polymorphism February, 2010 3 / 27
Types and classes Types
Types
In Java there exist 2 different kinds of types:
Primitive types: int, float, char, boolean,...Primitive types represent collection of valuesPrimitive types have operations associated that can be applied onthose values.Ex: int: +,-,*,/,%
Reference types:I ArraysI ClassesI Interfaces
J.M.Ribo ([email protected]) Polymorphism February, 2010 4 / 27
Types and classes Classes
Classes
A class is a a reference type with a representation (i.e., a collection ofattributes) and an implementation of its operations in terms of theattributes that constitute its representation.
Objects are instances of classes
Operations are applied to objects.
The representation or the implementation associated to a class can beincomplete. If this is the case, we have abstract classes.
J.M.Ribo ([email protected]) Polymorphism February, 2010 5 / 27
Notion of polymorphism
Notion of polymorphismConsider the following class:
pub l i c c l a s s T e s t P o l y g o n s {vo id showAreaAndPer imeter ( R e g u l a r P o l y g o n p ){
System . out . p r i n t l n ( ”Type o f p o l y g o n : ”+p . t o S t r i n g ( ) ) ;System . out . p r i n t l n ( ” Area=”+p . g e t A r e a ( ) ) ; // (3 )System . out . p r i n t l n ( ” P e r i m e t e r=”+p . g e t P e r i m e t e r ( ) ) ;System . out . p r i n t l n ( ” . . . . . . . . . . . . . . . . . . . . ” ) ;
}// . . . .
pub l i c s t a t i c vo id main ( S t r i n g [ ] a r g s )Square sq = new Square ( 1 2 . 0 ) ;
// sq i s a squa r e w i th edge l e n g t h =12.0
T r i a n g l e t r = new T r i a n g l e ( 6 . 0 ) ;// t r i s a t r i a n g l e w i th edge l e n g t h =6.0
showAreaAndPer imeter ( sq ) ; // (1 )showAreaAndPer imeter ( t r ) ; // (2 )
}// . . . .}J.M.Ribo ([email protected]) Polymorphism February, 2010 6 / 27
Notion of polymorphism
Notion of polymorphism
Clearly, the following output is expected:
Type of polygon: SquareArea=144.0Perimeter=48.0
........................Type of polygon: TriangleArea=7.8Perimeter=18.0
........................
J.M.Ribo ([email protected]) Polymorphism February, 2010 7 / 27
Notion of polymorphism
Notion of polymorphism
In order to achieve this behaviour, the instruction:p.getArea() in (3) should get associated with:
Square.getArea() in the first call (with sq)
Triangle.getArea() in the second call (with (tr)).
That is:
The operation call (getArea() ) at line (1) should be associated withdifferent operation bodies according to the runtime type of the object p.
J.M.Ribo ([email protected]) Polymorphism February, 2010 8 / 27
Notion of polymorphism
Notion of polymorphism
Polymorphism:
Polymorphism is the feature by which:
An object reference in a program code may refer to objects belongingto different classes at different moments throughout the execution ofthat programExample: The parameter p of showAreaAndPerimeter(RegularPolygon p)
refers on one occasion to a Square (1) and on another occasion to a Triangle (2)
AND
An operation call is associated to a different code according to theruntime type of the object on which that operation has been invokedExample: p.getArea() in (3) should get associated with:
I Square.getArea() in the first call (1)I Triangle.getArea() in the second call (2)
J.M.Ribo ([email protected]) Polymorphism February, 2010 9 / 27
Abstract classes and interfaces Abstract classes
Abstract classes
In order to deal with polymorphism we use abstract classes andinterfaces
An abstract class is a class which cannot be instantiatedAbstract classes usually provide a partial implementation (e.g., attributes,some implemented methods).This partial implementation is shared and completed by teir subclasses
J.M.Ribo ([email protected]) Polymorphism February, 2010 10 / 27
Abstract classes and interfaces Abstract classes
Abstract classesabs t rac t pub l i c c l a s s R e g u l a r P o l y g o n {
f i n a l protected double DEFAULTLENGTH =10. ;
protected double edgeLength ;
pub l i c R e g u l a r P o l y g o n ( ){t h i s . edgeLength = DEFAULTLENGTH ;
}pub l i c R e g u l a r P o l y g o n ( double l e n ){
t h i s . edgeLength = l e n ;}pub l i c double getEdgeLength ( ){
re tu rn edgeLength ;}pub l i c vo id se tEdg eLe ngth ( double edgeLen ){
t h i s . edgeLength = edgeLen ;}abs t rac t pub l i c double g e t A r e a ( ) ;
abs t rac t pub l i c double g e t P e r i m e t e r ( ) ;
pub l i c S t r i n g t o S t r i n g ( ){re tu rn ”Edge l e n g t h=”+t h i s . edgeLength+
” Area=”+t h i s . g e t A r e a ()+” P e r i m e t e r=”+t h i s . g e t P e r i m e t e r ( ) ;
}}
J.M.Ribo ([email protected]) Polymorphism February, 2010 11 / 27
Abstract classes and interfaces Abstract classes
pub l i c c l a s s Square extends R e g u l a r P o l y g o n {pub l i c Square ( ){
super ( ) ;}pub l i c Square ( double l e n ){
super ( l e n ) ;}pub l i c double g e t P e r i m e t e r ( ){
re tu rn t h i s . edgeLength ∗ 4 ;}pub l i c double g e t A r e a ( ){
re tu rn Math . pow ( t h i s . edgeLength , 2 ) ;}pub l i c S t r i n g t o S t r i n g ( ){
re tu rn ” Square : ”+super . t o S t r i n g ( ) ;
}}
J.M.Ribo ([email protected]) Polymorphism February, 2010 12 / 27
Abstract classes and interfaces Abstract classes
pub l i c c l a s s T r i a n g l e extends R e g u l a r P o l y g o n {double h e i g h t ;pub l i c T r i a n g l e ( ){
super ( ) ;t h i s . h e i g h t = Math . s q r t (
Math . pow ( t h i s . edgeLength ,2)−Math . pow ( t h i s . edgeLength / 2 , 2 ) ) ;
}pub l i c T r i a n g l e ( double l e n ){
super ( l e n ) ;t h i s . h e i g h t = Math . s q r t (
Math . pow ( t h i s . edgeLength ,2)−Math . pow ( t h i s . edgeLength / 2 , 2 ) ) ;
}pub l i c double g e t H e i g h t ( ){
re tu rn t h i s . h e i g h t ;}
J.M.Ribo ([email protected]) Polymorphism February, 2010 13 / 27
Abstract classes and interfaces Abstract classes
pub l i c double g e t P e r i m e t e r ( ){re tu rn t h i s . edgeLength ∗ 3 ;
}pub l i c double g e t A r e a ( ){
re tu rn t h i s . edgeLength ∗ t h i s . h e i g h t / 2 ;}pub l i c S t r i n g t o S t r i n g ( ){
re tu rn ” T r i a n g l e : ”+super . t o S t r i n g ()+” h e i g h t=”+t h i s . g e t H e i g h t ( ) ;
}}
J.M.Ribo ([email protected]) Polymorphism February, 2010 14 / 27
Abstract classes and interfaces Abstract classes
getArea() and getPerimeter()The operations getArea() and getPerimeter() cannot beimplemented at RegularPolygon since we do not know how tocalculate the area or the perimeter of a polygon without knowingwhich type of polygon it is (square, triangle, circumference...).
toString()Notice the code of the operation toString(). It can calculate thearea and perimeter of a polygon by calling getArea() andgetPerimeter(). However, toString() does not know, at compilationtime, which type of polygon it is dealing with
J.M.Ribo ([email protected]) Polymorphism February, 2010 15 / 27
Abstract classes and interfaces Abstract classes
Subclasses of RegularPolygon: getArea() getPerimeter()definition
The specific subclasses of RegularPolygon will implement theoperations (getArea() and getPerimeter()) with the appropriatecode (square: edgeLength*edgeLength; circumference:PI*radius*radius ...)
Subclasses of RegularPolygon: toString() redefinition
The specific subclasses of RegularPolygon redefine toString() inorder to generate a string that contains particular features of eachspecific type of regular polygon
J.M.Ribo ([email protected]) Polymorphism February, 2010 16 / 27
Abstract classes and interfaces Interfaces
Interfaces
An interface is a reference type that defines the behaviour of the objectsthat have that type in terms of operation headers.
Interfaces are implemented by classes.
When a class implements an interface, it must declare and implement allthe methods whose header have been defined in the interface body
Interfaces cannot:
Define attributes or
Implement the methods defined by them.
J.M.Ribo ([email protected]) Polymorphism February, 2010 17 / 27
Abstract classes and interfaces Interfaces
Interface examplespub l i c i n t e r f a c e Readab le { // (1 )
pub l i c vo id r e a d ( ) ;}
pub l i c c l a s s Newspaper implements Readab le { // (2 )pub l i c vo id r e a d ( ){
. . . . .}
}
pub l i c c l a s s TestReader {pub l i c s t a t i c vo id readAndComment ( Readab le r ){ // (3 )
. . .r . r e a d ( ) ;. . .
}pub l i c s t a t i c vo id main ( S t r i n g [ ] a r g s ){
Newspaper nwp = new NewsPaper ( . . . ) ;readAndComment ( nwp ) ; // (4 )
}}J.M.Ribo ([email protected]) Polymorphism February, 2010 18 / 27
Abstract classes and interfaces Interfaces
(1): An interface called Readable with a method read() has been createdThis interface provides the behaviour of reading. Any class that hasto offer this behaviour will implement the Readable interface
(2): The class Newspaper offers the reading behaviour. Hence, itimplements the Readable interface and implements the methodread() according to its specific meaning for the Newspaper classOther classes such as Book, Magazine, CD, DVD... could alsoimplement the Readable interface
(3): An operation ReadAndComment is defined with a parameter of theinterface ReadableAny object which is an instance of a class that implements Readablecan act as a parameter of this operation
(4): readAndComment(..) is called with a Newspaper object
J.M.Ribo ([email protected]) Polymorphism February, 2010 19 / 27
Abstract classes and interfaces Interfaces
Interface examples (2)
pub l i c i n t e r f a c e P l a y e r {pub l i c vo id p l a y ( ) ;pub l i c vo id s t o p ( ) ;pub l i c vo id pause ( ) ;pub l i c vo id f f ( ) ;pub l i c vo id rew ( ) ;pub l i c vo id s e t V o l ( i n t v o l ) ;
}
pub l i c c l a s s DVDPlayer implements P l a y e r {pub l i c vo id p l a y ( ) { . . . . }pub l i c vo id s t o p ( ) { . . . . }pub l i c vo id pause ( ) { . . . . }pub l i c vo id f f ( ) { . . . . }pub l i c vo id rew ( ) { . . . . }pub l i c vo id s e t V o l ( i n t v o l ) { . . . . }
}
J.M.Ribo ([email protected]) Polymorphism February, 2010 20 / 27
Abstract classes and interfaces Interfaces
Interfaces
If a class A implements an interface I then A is not a subclass of I. Itmerely implements all the methods defined in IThat is, the class A adheres to the behaviour defined by the interface I
A class may implement several interfaces. This means that A providesthe behaviour defined by ALL those implemented interfacesThis is the way provided by Java to deal with multiple inheritance
There can be hierarchies of interfaces
J.M.Ribo ([email protected]) Polymorphism February, 2010 21 / 27
Abstract classes and interfaces Abstract classes vs. Interfaces
Abstract classes vs. Interfaces
Abstract classes may have animplementation (they usuallyhave one!!!), although it may beincomplete.
Abstract classes are part of aclass hierarchy
Abstract classes must havenon-abstract subclasses thatimplement the operationsdeclared (but not implemented)in them
Interfaces cannot have eitherimplementated operations orattributes . Usually, they onlyhave operation headers
Classes implement interfaces,do not extend themTherefore, classes are notsubclasses of an interface
Classes that implement aninterface declare that they haveimplemented all the operationsdefined in that interface
A class may extend just anotherclass. However, a class mayimplement several interfaces
J.M.Ribo ([email protected]) Polymorphism February, 2010 22 / 27
Conversion and type checking
Downcast
Downcast
a reference type can be converted to a more particular reference type (i.e.,downcasted)
Example:
L i n k e d L i s t <Regu la rPo lygon > l r p = new L i n k e d L i s t <Regu la rPo lygon >;Square sq = new Square ( 1 9 . 0 ) ;
l r p . a d d F i r s t ( sq ) ; // (1 )
Square p = ( Square ) l r p . g e t F i r s t ( ) ; // (2 )
The operation LinkedList<RegularPolygon>.getFirst() returns aRegularPolygon. However, since the RegularPolygon that has beenadded at the begining of the list is a Square (1), it is clear thatgetFirst will get a Square.For this reason, it is possible to downcast lpr.getFirst() to Square,as it is done in (2)
J.M.Ribo ([email protected]) Polymorphism February, 2010 23 / 27
Conversion and type checking
A downcast will throw an exception in the case that an object isdowncasted to the wrong type:
The following code would have led to a ClassCastException :
t r y {L i n k e d L i s t <Regu la rPo lygon > l r p = new L i n k e d L i s t <Regu la rPo lygon >;Square sq = new Square ( 1 9 . 0 ) ;
l r p . a d d F i r s t ( sq ) ;
T r i a n g l e p = ( T r i a n g l e ) l r p . g e t F i r s t ( ) ;}catch ( C l a s s C a s t E x c e p t i o n e ) { . . . . t h i s code w i l l be e x e c u t e d . . . }
J.M.Ribo ([email protected]) Polymorphism February, 2010 24 / 27
Conversion and type checking
Type checking
The runtime type of an object can be checked:
T r i a n g l e p ;
i f ( l r p . g e t F i r s t ( ) i n s t anceo f T r i a n g l e )p = ( T r i a n g l e ) l r p . g e t F i r s t ( ) ;
J.M.Ribo ([email protected]) Polymorphism February, 2010 25 / 27
Reflection
Reflection
The Java class Class<T> is a special class such that any other class canbe seen as an instance of itThat is, a class can be seen as an object instance of Class<T>
In other words, Class<T> is a metaclass (a class, whose instances areclasses themselves)Two operations of Class<T>:
static Class<?> forName(String className)
Returns the Class object associated with the class or interface withthe given string name
boolean isInstance(Object obj)
Determines if the specified Object is an instance of this Class
J.M.Ribo ([email protected]) Polymorphism February, 2010 26 / 27
Reflection
Reflection
Example:
c l a s s A {}
pub l i c c l a s s R e f l e c t i o n E x a m p l e {pub l i c s t a t i c vo id main ( S t r i n g [ ] a r g s ){
t r y {C l a s s c l s = C l a s s . forName ( ”A” ) ;i f ( c l s . i s I n s t a n c e (new A ( ) ) . . . .
}catch ( Throwable e ) {
System . e r r . p r i n t l n ( e ) ;}
}}
J.M.Ribo ([email protected]) Polymorphism February, 2010 27 / 27