Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java...

47
Inheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Inheritance and Polymorphism Pieter van den Hombergh Thijs Dorssers Stefan Sobek Fontys Hogeschool voor Techniek en Logistiek February 10, 2017 HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 1/45

Transcript of Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java...

Page 1: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

Inheritance and Polymorphism

Pieter van den HomberghThijs DorssersStefan Sobek

Fontys Hogeschool voor Techniek en Logistiek

February 10, 2017

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 1/45

Page 2: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

TopicsJava InheritanceClass hierarchy - An example

VisibilityI can see what you can’tConstructors and inheritancePolymorphism

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 2/45

Page 3: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 3/45

Page 4: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 3/45

Page 5: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 3/45

Page 6: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 4/45

Page 7: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

The implicit base class Object

Classes without the extends-keyword automaticallyinherit from Object

Object is an implicit super classEach class inherits either directly or indirectly fromjava.lang.Object

All visible attributes and methods, like toString(), areinherited

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 5/45

Page 8: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 6/45

Page 9: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 7/45

Page 10: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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 ;

}

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 8/45

Page 11: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

Example Human

public static void main ( String [] args ) {Student theStud = new Student ();theStud . name = " Richard Stallman ";

}

Class Student can use the inherited attributes name andeyeColor

Changes 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

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 9/45

Page 12: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

peekabo:I can see what you can’t

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 10/45

Page 13: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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 Ü private

Protected -protection is weaker than package-private!

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 11/45

Page 14: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

Visibility table

Table: Normalized visibility table.

Modifier Class Package Subclass Worldpublic y y y yprotected y y y -

(default) y y - -private y - - -

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 12/45

Page 15: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 13/45

Page 16: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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

}

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 14/45

Page 17: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 15/45

Page 18: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 16/45

Page 19: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 17/45

Page 20: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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 specificHOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 18/45

Page 21: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 19/45

Page 22: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

Override a method

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

}}

}

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 20/45

Page 23: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

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.ObjectHOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 21/45

Page 24: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Inheritance andPolymorphism

HOMDOSSOB

Java Inheritance

Example I

Visibilitypeekabo

Constructors

Polymorphism

Not all understood? For next time read:

Introduction to Java Programming: Chapter 11

Questions?Questions or remarks?

HOMDOSSOB/FHTenL Inheritance and Polymorphism February 10, 2017 22/45

Page 25: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

Polymorphism, abstract classes andinterfaces

Part II

Pieter van den HomberghThijs DorssersStefan Sobek

Fontys Hogeschool voor Techniek en Logistiek

February 10, 2017

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 23/45

Page 26: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

TopicsPolymorphismAbstract classes and methods

Interfaces

Java8 interfaces: default and static

multiple inheritance of implementationExample: ParentsExample: Child interfaces

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 24/45

Page 27: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

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

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 25/45

Page 28: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

Polymorphism - Example

public class Human extends Object {...

@Overridepublic String toString (){

return "[ Human :...";}

}

public class Student extends Human {...

@Overridepublic String toString (){

return "[ Student :...";}

}

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 26/45

Page 29: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

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?

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 27/45

Page 30: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

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

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 28/45

Page 31: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

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.

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 29/45

Page 32: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

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.

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 30/45

Page 33: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

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

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 31/45

Page 34: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

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?

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 32/45

Page 35: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

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 ();}

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 33/45

Page 36: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

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

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 34/45

Page 37: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

Interfaces

Instead of class, interface is usedMethods in interfaces don’t have a bodyAll methods are automatically abstract and public

Constructors are useless and therefore not allowedInstance variables are not allowed either,static-variables however are allowed (automaticallyfinal)

public interface Callable <T> {

T call ();

}

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 35/45

Page 38: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

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 ) {...}}

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 36/45

Page 39: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

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 ) {...}}

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 37/45

Page 40: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

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 ;

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 38/45

Page 41: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

Interfaces

What will happen now?

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 39/45

Page 42: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

Interfaces as specification

Separation of functionality and implementationClients communicate implementation-independentAlternative implementations can be used

T

ArrayList

T

«interface»List

T

LinkedList

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 40/45

Page 43: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

Interfaces vs. Abstract classes

public interface Callable <T> {

T call ();

}

public abstract class Callable <T> {

abstract T call ();

}

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 41/45

Page 44: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

Java8 interfaces: default and static 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 Java 8, in combination with λexpression.

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 42/45

Page 45: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

Multiple inheritance example, parents

interface AnInterface {

default String getName () {return "An";

}}

interface BnInterface {

default String getName () {return "Bn";

}}

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 43/45

Page 46: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

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 a class implementing two interfaces-methods withthe same signature must also specify which variant to select,using the same construction as above.See DEMO

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 44/45

Page 47: Inheritance and Polymorphism - java2. · PDF fileInheritance and Polymorphism HOM DOS SOB Java Inheritance Example I Visibility peekabo Constructors Polymorphism Known Between objects,

Polymorphism,abstract classesand interfaces

Part II

HOMDOSSOB

Polymorphism

Abstract classes andmethods

Interfaces

Java8

multiple I.Parents

Children

Any open issues?Not all understood? For next time read:

Introduction to Java Programming: Chapter 11Java 8 tutorial on default methodshttp://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

Questions?Questions or remarks?

HOMDOSSOB/FHTenL Polymorphism, abstract classes and interfacesPart II February 10, 2017 45/45