polymorphism - ocw.udl.cat

of 27/27
Polymorphism Josep Maria Rib´ o [email protected] February, 2010 J.M.Rib´o ([email protected]) Polymorphism February, 2010 1 / 27

Post on 05-Jan-2022

0 views

Category:

Documents

0 download

Embed Size (px)

TRANSCRIPT

Polymorphismndex
2 Notion of polymorphism
3 Abstract classes and interfaces Abstract classes Interfaces Abstract classes vs. Interfaces
4 Conversion and type checking
5 Reflection
Types and classes Types
Types
Type
A type characterizes a collection of objects or values in terms of their behaviour. This behaviour is modelled in terms of operations that can be performed on those objects/values.
Examples of types: int, float, char, String, Student, Comparable, Readable, MediaPlayer...
Operations associated to int: +,-,*, /, %
Types and classes Types
Primitive types: int, float, char, boolean,... Primitive types represent collection of values Primitive types have operations associated that can be applied on those values. Ex: int: +,-,*,/,%
Reference types: I Arrays I Classes I 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 of attributes) and an implementation of its operations in terms of the attributes that constitute its representation.
Objects are instances of classes
Operations are applied to objects.
The representation or the implementation associated to a class can be incomplete. If this is the case, we have abstract classes.
J.M.Ribo ([email protected]) Polymorphism February, 2010 5 / 27
Notion of polymorphism
Notion of polymorphism Consider 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 ){
} // . . . .
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
Type of polygon: Square Area=144.0 Perimeter=48.0
........................ Type of polygon: Triangle Area=7.8 Perimeter=18.0
........................
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 with different 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 is the feature by which:
An object reference in a program code may refer to objects belonging to different classes at different moments throughout the execution of that program Example: 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 the runtime type of the object on which that operation has been invoked Example: 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 and interfaces
An abstract class is a class which cannot be instantiated Abstract 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 classes abs 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+
} }
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 ( ){
} }
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 ( ){
} }
Abstract classes and interfaces Abstract classes
getArea() and getPerimeter() The operations getArea() and getPerimeter() cannot be implemented at RegularPolygon since we do not know how to calculate the area or the perimeter of a polygon without knowing which type of polygon it is (square, triangle, circumference...).
toString() Notice the code of the operation toString(). It can calculate the area and perimeter of a polygon by calling getArea() and getPerimeter(). However, toString() does not know, at compilation time, 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 the operations (getArea() and getPerimeter()) with the appropriate code (square: edgeLength*edgeLength; circumference: PI*radius*radius ...)
Subclasses of RegularPolygon: toString() redefinition
The specific subclasses of RegularPolygon redefine toString() in order to generate a string that contains particular features of each specific 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 objects that have that type in terms of operation headers.
Interfaces are implemented by classes.
When a class implements an interface, it must declare and implement all the methods whose header have been defined in the interface body
Interfaces cannot:
J.M.Ribo ([email protected]) Polymorphism February, 2010 17 / 27
Abstract classes and interfaces Interfaces
Interface examples pub 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 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 created This interface provides the behaviour of reading. Any class that has to offer this behaviour will implement the Readable interface
(2): The class Newspaper offers the reading behaviour. Hence, it implements the Readable interface and implements the method read() according to its specific meaning for the Newspaper class Other classes such as Book, Magazine, CD, DVD... could also implement the Readable interface
(3): An operation ReadAndComment is defined with a parameter of the interface Readable Any object which is an instance of a class that implements Readable can 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)
}
}
Abstract classes and interfaces Interfaces
Interfaces
If a class A implements an interface I then A is not a subclass of I. It merely implements all the methods defined in I That is, the class A adheres to the behaviour defined by the interface I
A class may implement several interfaces. This means that A provides the behaviour defined by ALL those implemented interfaces This 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 an implementation (they usually have one!!!), although it may be incomplete.
Abstract classes are part of a class hierarchy
Abstract classes must have non-abstract subclasses that implement the operations declared (but not implemented) in them
Interfaces cannot have either implementated operations or attributes . Usually, they only have operation headers
Classes implement interfaces, do not extend them Therefore, classes are not subclasses of an interface
Classes that implement an interface declare that they have implemented all the operations defined in that interface
A class may extend just another class. However, a class may implement 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 a RegularPolygon. However, since the RegularPolygon that has been added at the begining of the list is a Square (1), it is clear that getFirst 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 is downcasted 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
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 can be seen as an instance of it That 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 are classes themselves) Two operations of Class<T>:
static Class<?> forName(String className)
Returns the Class object associated with the class or interface with the 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 ) {
} }
Óndex