inheritance and polymorphism - java2.fontysvenlo.org · inheritance and polymorphism hee hvd hom...
TRANSCRIPT
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Inheritance and Polymorphism
Uwe van HeeschRichard van den Ham
Pieter van den HomberghThijs Dorssers
Fontys Hogeschool voor Techniek en Logistiek
February 21, 2015
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 1/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Topics
Java InheritanceClass hierarchy - An example
VisibilityI can see what you can’tConstructors and inheritancePolymorphism
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 2/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Known
Between objects, relationships exist
An association represents a Has-relationshipA human being has two legsA chair has 4 chair legsA car has 4 wheels
Beside, a Is-a-relationship existsApples and pears are fruit speciesStudents and lecturers are humansThe type defines characteristics for its elements
Each human being has an eye colorEach human being has a hair colorEach human being has a size
Java represents this relationship by inheritanceParents give their Childs characteristics
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 3/45
February 21, 2015
1
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Known
Between objects, relationships existAn association represents a Has-relationship
A human being has two legsA chair has 4 chair legsA car has 4 wheels
Beside, a Is-a-relationship existsApples and pears are fruit speciesStudents and lecturers are humansThe type defines characteristics for its elements
Each human being has an eye colorEach human being has a hair colorEach human being has a size
Java represents this relationship by inheritanceParents give their Childs characteristics
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 3/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Known
Between objects, relationships existAn association represents a Has-relationship
A human being has two legsA chair has 4 chair legsA car has 4 wheels
Beside, a Is-a-relationship existsApples and pears are fruit speciesStudents and lecturers are humansThe type defines characteristics for its elements
Each human being has an eye colorEach human being has a hair colorEach human being has a size
Java represents this relationship by inheritanceParents give their Childs characteristics
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 3/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Java Inheritance
Java defines classes in hierarchical relationshipsTherefore, classes have a Is-a-relationship with theirparent classThe keyword extends shows that a class is derivedfrom another classTherefore, a class becomes a sub classThe parent class is the super classThe sub class inherits all visible characteristics of thesuper class
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 4/45
February 21, 2015
2
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
The implicit base class Object
Classes without the extends-keyword automaticallyinherit from ObjectObject is an implicit super classEach class inherits either directly or indirectly fromjava.lang.ObjectAll visible attributes and methods, like toString(), areinherited
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 5/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
No Multiple inheritance in Java
Java only allows single inheritanceBehind the extends-keyword, only one super class isallowedao C++, Python and Perl allow Multiple Inheritance.Why does java not?
new SubClass().doSomething(); Do what???
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 6/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Example Person
Figure : A class hierarchy for our school
Students and Lecturers are Humanswith ao a name and an eye colorTeamLeader could have been a sub class of Lecturer
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 7/45
February 21, 2015
3
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Example Human
package nl. fontys . pro2 . week1 ;
import java .awt. Color ;
public class Human {protected String name ;protected Color eyeColor ;
}
package nl. fontys . pro2 . week1 ;
public class Student extends Human {private Number number ;
}
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 8/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Example Human
public static void main ( String [] args ) {Student theStud = new Student ();theStud . name = " Richard Stallman ";
}
Class Student can use the inherited attributes name andeyeColorChanges in a super class are automatically representedin sub classesTherefore, a sub class has a very strong coupling to itssuper classSuper classes don’t know their sub classes
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 9/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
peekabo:I can see what you can’t
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 10/45
February 21, 2015
4
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Visibility
Sub classes inherit all visible characteristics from theirsuper classpublic: visible for all classespackage-private: visible for all classes in the samepackageprivate: only visible within class (including containedinner class)In addition: protected:
protected attributes and methods are inherited by allsub classesare visible for all classes in the same package
public Ü protected Ü package-private Ü privateProtected -protection is weaker than package-private!
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 11/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Visibility table
Table : Normalized visibility table.
Modifier Class Package Subclass Worldpublic y y y yprotected y y y -
(default) y y - -private y - - -
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 12/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Usage of constructors with inheritance
In contrast to methods, constructors are not inheritedSub classes need a constructor to enable objects to becreatedWithin the constructor, Java automatically invokes thesuper class constructorWhen no constructor has explicitly been defined, theimplicit default constructor is used
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 13/45
February 21, 2015
5
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
A super constructor
super() invokes the super constructor explicitlyThe default constructor is always invoked implicitlysuper can invoke parameterized constructorsMandatory, if super class does not have defaultconstructor
public class Student extends Human {public Student ( Number number ){ ... }
}
public class StudAssistant extends Student {public StudAssistant ( Number sNumber ){
super ( sNumber );}
}
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 14/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Summary constructors and methodsConstructors
can’t be abstract, final, native, static orsynchronizeddon’t have a return value, even not voidare not inheritedCan have all visibility attributesthis(...) refers to another constructor in the sameclasssuper(...) invokes a constructor of super class
Methodscan be public, protected, package-private, private,abstract, final, native, static or synchronizedcan have return values, or voidVisible methods are inheritedInherited visibility cannot be changedthis is a reference to the current instance of the classWith super, overridden methods of the superclass canbe invoked
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 15/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Static and dynamic types
Seemingly trivial relationshipsA Student is a HumanA Lecturer is a HumanA Human is an ObjectA Student is a Student
In Java:
Human studentIsHuman = new Student ();Human lecturerIsHuman = new Lecturer ();Object humanIsObject = new Human ();Student studentIsStudent = new Student ();
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 16/45
February 21, 2015
6
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Static and Dynamic types
The declared type is the so-called static typeThe initialised type is the dynamic typeThe declared type or L-Value is configured with theirstatic type. An object knows its dynamic type.Variables are treated as being of a static type
Human studHum = new Student ();System .out. println ( studHum . getName ());// The following will not work:System .out. println ( studHum . getSNumber ());
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 17/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Static and dynamic types
Variables can not simply be initialised with lesser1 types.In case of the correct dynamic type, a typecast helpsinstanceof verifies dynamic types
Human stud = new Student ();// next line will not work:Student stud2 = stud ;// This one will:Student stud3 = ( Student ) stud ;// Because stud has the dynamic type Studentif( stud instanceof Student ){
// instanceof tests the dynamic Typ}
1less specificHEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 18/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Override a method
Methods of Super classes are overwritten whenThe name andthe list of parameters (number of params and theirtype, not their name)and return typeexactly match that of the super classes method
The annotation @Override lets the compiler also checkwhether a method is actually and correctly overwrittenThe method of the superclass is then ruled out, right?Example: override the toString() method of Object
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 19/45
February 21, 2015
7
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Override a methodmakes calling overridden methods possibleYou can only reach one level higher with super:Chaining of super keywording at a deeper inheritancehierarchy is not possibleSuper methods are not accessible from the outside. Acall to a super.... method can only be made onthis, inside the defining class, not any other object.
public class Student extends Human {...
@Overridepublic void setName ( String name ) {
if( isNiceName ( name )){super . setName ( name );
}}
}
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 20/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
prohibit method override
The keyword final prohibits overriding.In classes, thereby prohibiting extension
example final class Integerfor methods, thereby prohibiting that they can beoverridden
example: public final wait()2
Quiz: could you come up with a use for aprotected final method?
2Defined in this way in java.lang.ObjectHEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 21/45
Inheritance andPolymorphism
HEEHVDHOMDOS
Java InheritanceExample I
VisibilitypeekaboConstructorsPolymorphism
Not all understood? For next time read:
BlueJ: Chapter 8.2 - 8.11
Questions?Questions or remarks?
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 22/45
February 21, 2015
8
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Inheritance and Polymorphism
Uwe van HeeschRichard van den Ham
Pieter van den HomberghThijs Dorssers
Fontys Hogeschool voor Techniek en Logistiek
February 21, 2015
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 23/45
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Topics
PolymorphismAbstract classes and methods
Interfaces
Java8 default methodsmultiple inheritance of implementationExample: ParentsExample: Child interfaces
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 24/45
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Polymorphism
Polymorphism is the ability to provide a single interface toentities of different types
Visible methods of super classes also exist in sub classesSuper classes can predefine implementations, which canbe overwritten, if requiredWe can however be sure the methods exist
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 25/45
February 21, 2015
9
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Polymorphism - Example
public class Human extends Object {...
@Overridepublic String toString (){
return "[ Human :...";}
}
public class Student extends Human {...
@Overridepublic String toString (){
return "[ Student :...";}
}
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 26/45
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Polymorphism - Example
Student student = new Student ();System .out. println ( student );
Human human = new Student ();System .out. println ( human );
Object object = new Student ();System .out. println ( object );
What will the output look like?
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 27/45
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Polymorphism - Example
During runtime, the method toString() fromStudent will always be usedIn contrast to the compiler, the runtime environmentknows the dynamic typeThis is called dynamic binding, because the actualtype of an object is only determined at runtimeThe method that is the deepest one in the classhierarchy is chosen
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 28/45
February 21, 2015
10
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Polymorphism - Example
-name : String-eyeColor : Color
+toString() : String
Human
-sNumber : Number
+toString() : String
Student
-salary : Double
Lecturer
+toString() : String
Object
At runtime the method that is most specificis choosen.
Although declared 'deepest' in the class hierarchy, it is the first in the list consulted by the jvm.
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 29/45
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Exceptions on polymorphism
Not all methods are dynamically boundOnly overridden methods participateMethods which can’t be overridden will bound staticallyprivate, static and final methods fall in thiscategory.
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 30/45
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Abstract classes
Abstract classes can’t be instantiatedAn abstract class can be used as a static (ordeclaration) type.Useful, for example for classes which are only used assuper class, to provide signatures for sub classesThe keyword abstract identifies abstract classesAbstract classes are the opposite of concrete classes
public abstract class Human {...}
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 31/45
February 21, 2015
11
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Abstract classes
Abstract classes are often used in inheritanceThey behave like concrete classesA subclass can extend an abstract class and can beabstract itself again
Human stud1 = new Student ();Human [] humans = new Human [] {new Student () , new ←↩
Lecturer () };
Where could abstract classes be used for as well?
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 32/45
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Abstract methods
Methods in abstract classes could also be abstractThey only define a method signature for the sub classConcrete sub classess have to implement these
public abstract class Human extends Object {...
protected abstract void dress ();}
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 33/45
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
InterfacesIt’s difficult to give classes multiple types by usinginheritanceInheritance is always done in order, Human inheritsfrom Object, Students inherits from Human, etc.Sometimes, classes need to have types from differenthierarchies
#name : String#eyeColour : Color
+toString() : String
Human
-sNumber : Number
+toString() : String+call() : T
Student
+call() : T
<<Interface>>Callable<T>
+call() : Car
Company
T
T
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 34/45
February 21, 2015
12
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Interfaces
Instead of class, interface is usedMethods in interfaces don’t have a bodyAll methods are automatically abstract and publicConstructors are useless and therefore not allowedInstance variables are not allowed either,static-variables however are allowed (automaticallyfinal)
public interface Callable <T> {
T call ();
}
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 35/45
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Interfaces
public class Student extends Humanimplements Callable {
// ...public void call () {...}
}
public class Student extends Humanimplements Callable , Annoyable {// ...
public void call () {...}
public StressLevel annoy ( double degree ) {...}}
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 36/45
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Interfacespublic class Student extends Human
implements Callable {// ...public void call () {...}
}
public class Student extends Humanimplements Callable , Annoyable {// ...
public void call () {...}
public StressLevel annoy ( double degree ) {...}}
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 37/45
February 21, 2015
13
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Interfaces
Classes can implement multiple interfacesInterfaces can extend zero, one or multiple otherinterfacesThey allow objects to act in different rolesA powerful object can be reduced to a single methodUsage analogous to usage of abstract classes
Callable callable = new Student ();Human human = ( Student ) callable ;
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 38/45
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Interfaces
What will happen now?
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 39/45
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Interfaces as specification
Separation of functionality and implementationClients communicate implementation-independentAlternative implementations can be used
T
ArrayList
T
«interface»List
T
LinkedList
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 40/45
February 21, 2015
14
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Interfaces vs. Abstract classes
public interface Callable <T> {
T call ();
}
public abstract class Callable <T> {
abstract T call ();
}
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 41/45
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Java8 default methodsTo be able to extend of the framework without breakingexisting interfaces and implementing classes, Java 8introduces a few new concepts.
static methods (implementations) in interfaces.default method (implementations!) in interfaces.It allows the extension of interfaces without breakingexisting implementing classes.The static methods are typically helpers for the defaultmethods.It also implies multiple inheritance for said defaultmethods.If a conflict is possible, the implementation programmermust help the compiler by specifying which defaultvariant method is to be taken.The first use case of this extension is the streamframework, introduced, in combination with λexpression.
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 42/45
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Multiple inheritance example, parents
interface AnInterface {
default String getName () {return "An";
}}
interface BnInterface {
default String getName () {return "Bn";
}}
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 43/45
February 21, 2015
15
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Multiple inheritance example, child
interface CnInterface extends AnInterface ,BnInterface {
// resolve which super to use.// also works in implementing classes@Overridedefault String getName () {
return AnInterface . super . getName ();}
}
Note that an class implementing two interfaces-methodswith the same signature must also specify which variant toselect, using the same construction as above.See DEMO
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 44/45
Inheritance andPolymorphism
HEEHVDHOMDOS
PolymorphismAbstract classes andmethodsInterfaces
Java8 defaultmethodsmultiple I.ParentsChildren
Any open issues?
Not all understood? For next time read:BlueJ: Chapters 9 and 10Java 8 tutorial on default methodshttp://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
Questions?Questions or remarks?
HEEHVDHOMDOS/FHTenL Inheritance and Polymorphism February 21, 2015 45/45
February 21, 2015
16