Pieter van den Hombergh Thijs Dorssers Stefan Sobek. January 11, 2018

Similar documents
Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

Pieter van den Hombergh Thijs Dorssers Richard van den Ham. May 17, 2018

The Enum Type. Pieter van den Hombergh Richard van den Ham. March 1, Fontys Hogeschool voor Techniek en Logistiek. The Enum Type HOM HVD

Object Oriented Programming. Java-Lecture 11 Polymorphism

What is Inheritance?

Pieter van den Hombergh Richard van den Ham. March 1, 2018

CS 251 Intermediate Programming Inheritance

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. June 8, 2017

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Java Object Oriented Design. CSC207 Fall 2014

Lecture 18 CSE11 Fall 2013 Inheritance

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Programming II (CS300)

CS313D: ADVANCED PROGRAMMING LANGUAGE

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Lambda Expressions and Java 8 Streams. Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh. Contents of this talk.

CS111: PROGRAMMING LANGUAGE II

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Chapter 5. Inheritance

Declarations and Access Control SCJP tips

Class, Variable, Constructor, Object, Method Questions

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Inheritance -- Introduction

Pieter van den Hombergh Richard van den Ham. February 8, 2018

CS-202 Introduction to Object Oriented Programming

Inheritance (continued) Inheritance

Inheritance and Polymorphism

ECE 122. Engineering Problem Solving with Java

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Thijs Dorssers, Pieter van den Hombergh, Richard van den Ham. May 24, 2018

CS313D: ADVANCED PROGRAMMING LANGUAGE

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

More On inheritance. What you can do in subclass regarding methods:

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

1 Shyam sir JAVA Notes

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Practice for Chapter 11

Inheritance and Polymorphism

Programming II (CS300)

Chapter 5 Object-Oriented Programming

Implements vs. Extends When Defining a Class

25. Generic Programming

Inheritance (Outsource: )

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Inheritance. Transitivity

Compaq Interview Questions And Answers

More Relationships Between Classes

CMSC 132: Object-Oriented Programming II

CS111: PROGRAMMING LANGUAGE II

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Inheritance and Polymorphism

Inheritance, Polymorphism, and Interfaces

CMSC 132: Object-Oriented Programming II

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object

Chapter 6 Introduction to Defining Classes

Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright

First IS-A Relationship: Inheritance

Inheritance and Polymorphism. CS180 Fall 2007

Lecture 4: Extending Classes. Concept

Inheritance and Polymorphism

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Chapter 14 Abstract Classes and Interfaces

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5

Data Structures (list, dictionary, tuples, sets, strings)

C++ Important Questions with Answers

Java classes cannot extend multiple superclasses (unlike Python) but classes can implement multiple interfaces.

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

COP 3330 Final Exam Review

Java Fundamentals (II)

Java: introduction to object-oriented features

Prototype Description. Interpreter. interpreter Calculator Design Rationales. Prototype Participants. Interpreter with Factory Method.

PROGRAMMING LANGUAGE 2

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

ITI Introduction to Computing II

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Classes and Inheritance Extending Classes, Chapter 5.2

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Fontys Hogeschool voor Techniek en Logistiek. March 13, 2018

CS Programming I: Inheritance

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

Chapter 10 Classes Continued. Fundamentals of Java

CS 112 Programming 2. Lecture 10. Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces

ITI Introduction to Computing II

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Unit 4 - Inheritance, Packages & Interfaces

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

OVERRIDING. 7/11/2015 Budditha Hettige 82

Lecture 2: Java & Javadoc

Transcription:

Inheritance and Inheritance and Pieter van den Hombergh Thijs Dorssers Stefan Sobek Java Inheritance Example I Visibility peekabo Constructors Fontys Hogeschool voor Techniek en Logistiek January 11, 2018 /FHTenL Inheritance and January 11, 2018 1/44

Topics Java Inheritance Class hierarchy - An example Inheritance and Java Inheritance Example I Visibility peekabo Constructors Visibility I can see what you can t Constructors and inheritance /FHTenL Inheritance and January 11, 2018 2/44

Known Between objects, relationships exist Inheritance and Java Inheritance Example I Visibility peekabo Constructors /FHTenL Inheritance and January 11, 2018 3/44

Known Inheritance and Between objects, relationships exist An association represents a Has-a-relationship A human being has two legs A chair has 4 chair legs A car has 4 wheels Car has 4..n 1 Wheel Java Inheritance Example I Visibility peekabo Constructors /FHTenL Inheritance and January 11, 2018 3/44

Known Between objects, relationships exist An association represents a Has-a-relationship A human being has two legs A chair has 4 chair legs A car has 4 wheels Also, a Is-a-relationship exists Apples and pears are fruit species Students and lecturers are humans The type defines characteristics for its elements Every human being has an eye color Every human being has a hair color Every human being has a size Java represents this relationship by inheritance give their Childs characteristics Car Student has 4..n 1 Human Wheel Teacher Inheritance and Java Inheritance Example I Visibility peekabo Constructors /FHTenL Inheritance and January 11, 2018 3/44

Java Inheritance Java defines classes in hierarchical relationships Therefore, classes have a Is-a-relationship with their parent class The keyword extends shows that a class is derived from another class Therefore, a class becomes a sub class The parent class is the super class The sub class inherits all visible characteristics of the super class Inheritance and Java Inheritance Example I Visibility peekabo Constructors /FHTenL Inheritance and January 11, 2018 4/44

The implicit base class Object Classes without the extends-keyword automatically inherit from Object Object is an implicit super class Every class inherits either directly or indirectly from java.lang.object All visible attributes, like tostring(), are inherited Inheritance and Java Inheritance Example I Visibility peekabo Constructors /FHTenL Inheritance and January 11, 2018 5/44

No Multiple inheritance in Java Java only allows single inheritance Behind the extends-keyword, only one super class is allowed languages like C++, Python, and Perl allow Multiple Inheritance. Why does java not? Inheritance and Java Inheritance Example I Visibility peekabo Constructors new SubClass().doSomething(); Do what??? /FHTenL Inheritance and January 11, 2018 6/44

Example Person Inheritance and Java Inheritance Example I Visibility peekabo Constructors Figure: A class hierarchy for our school Students and Lecturers are Humans with ao a name and an eye color TeamLeader could have been a sub class of Lecturer /FHTenL Inheritance and January 11, 2018 7/44

Example Human package nl. fontys. pro2. week1 ; import java. awt. Color ; public class Human { String name ; Color eyecolor ; Inheritance and Java Inheritance Example I Visibility peekabo Constructors package nl. fontys. pro2. week1 ; public class Student extends Human { Number number ; /FHTenL Inheritance and January 11, 2018 8/44

Example Human public static void main ( String [] args ) { Student thestud = new Student (); thestud. name = " Richard Stallman "; Class Student can use the inherited attributes name and eyecolor Changes in a super class are automatically represented in sub classes Therefore, a sub class has a very strong coupling to its super class Super classes don t know their sub classes Inheritance and Java Inheritance Example I Visibility peekabo Constructors /FHTenL Inheritance and January 11, 2018 9/44

peekabo:i can see what you can t Inheritance and Java Inheritance Example I Visibility peekabo Constructors /FHTenL Inheritance and January 11, 2018 10/44

Visibility Sub classes inherit all visible characteristics from their super class public: visible for all classes package-private: visible for all classes in the same package private: only visible within class (including contained inner class) In addition: protected: protected attributes are inherited by all sub classes are visible for all classes in the same package In the visibility sense: public > protected > package-private > private Protected -protection is weaker than package-private! Inheritance and Java Inheritance Example I Visibility peekabo Constructors /FHTenL Inheritance and January 11, 2018 11/44

Visibility table Inheritance and Java Inheritance Example I Table: Normalized visibility table. Visibility peekabo Constructors Modifier Class Package Subclass World public y y y y protected y y y - (default) y y - - private y - - - /FHTenL Inheritance and January 11, 2018 12/44

Usage of constructors with inheritance When a an object is created the following happens: The JVM allocates memory for the object, then the constructors are called in order of hierarchy, top to bottom. In contrast to methods, constructors are not inherited Sub classes need a constructor to enable objects to be created Within the constructor, Java automatically invokes the super class default-constructor When no constructor has explicitly been defined, the implicit default constructor is used Inheritance and Java Inheritance Example I Visibility peekabo Constructors /FHTenL Inheritance and January 11, 2018 13/44

A super constructor super() invokes the super constructor explicitly The default constructor is always invoked implicitly super can invoke parameterized constructors Mandatory, if super class does not have default constructor Inheritance and Java Inheritance Example I Visibility peekabo Constructors public class Student extends Human { public Student ( Number number ){... public class StudAssistant extends Student { public StudAssistant ( Number snumber ){ super ( snumber ); /FHTenL Inheritance and January 11, 2018 14/44

Summary constructors Constructors can t be abstract, final, native, static or synchronized don t have a return value, even not void are not inherited Can have any of visibility attributes this(...) refers to another constructor in the same class super(...) invokes a constructor of super class Methods can be public, protected, package-private, private, abstract, final, native, static or synchronized can have return values, or void Visible methods are inherited Inherited visibility cannot be changed this is a reference to the current instance of the class With super, overridden methods of the superclass can be invoked Inheritance and Java Inheritance Example I Visibility peekabo Constructors /FHTenL Inheritance and January 11, 2018 15/44

,, Pieter van den Hombergh Thijs Dorssers Stefan Sobek Fontys Hogeschool voor Techniek en Logistiek January 11, 2018 /FHTenL, January 11, 2018 16/44

Static and dynamic types Seemingly trivial relationships A Student is a Human A Lecturer is a Human A Human is an Object A Student is a Student In Java: Human studentishuman = new Student (); Human lecturerishuman = new Lecturer (); Object humanisobject = new Human (); Student studentisstudent = new Student ();, /FHTenL, January 11, 2018 17/44

Static and Dynamic types The declared type is the so-called static type The initialised type is the dynamic type The declared type or L-Value is configured with their static 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 ());, /FHTenL, January 11, 2018 18/44

Static and dynamic types Variables can not simply be initialised with lesser 1 types. In case of the correct dynamic type, a typecast helps instanceof 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 Student if( stud instanceof Student ){ // instanceof tests the dynamic Typ, 1 less specific /FHTenL, January 11, 2018 19/44

Override a method Methods of Super classes are overwritten when The name and the list of parameters (number of params and their type, not their name) and return type exactly match that of the super classes method The annotation @Override lets the compiler also check whether a method is actually and correctly overwritten The method of the superclass is then ruled out, right? Example: override the tostring() method of Object, /FHTenL, January 11, 2018 20/44

Override a method makes calling overridden methods possible You can only reach one level higher with super: Chaining of super keywording at a deeper inheritance hierarchy is not possible Super methods are not accessible from the outside. A call to a super... method can only be made on this, inside the defining class, not any other object. public class Student extends Human {... @Override public void setname ( String name ) { if( isnicename ( name )){ super. setname ( name );, /FHTenL, January 11, 2018 21/44

prohibit method override The keyword final prohibits overriding. In classes, thereby prohibiting extension example final class Integer for methods, thereby prohibiting that they can be overridden example: public final wait() 2 Quiz: could you come up with a use for a protected final method?, 2 Defined in this way in java.lang.object /FHTenL, January 11, 2018 22/44

Topics interfaces: default and static, multiple inheritance of implementation Example: Example: Child interfaces /FHTenL, January 11, 2018 23/44

is the ability to provide a single interface to entities of different types Visible methods of super classes also exist in sub classes Super classes can predefine implementations, which can be overwritten, if required We can however be sure the methods exist, /FHTenL, January 11, 2018 24/44

- Example p u b l i c c l a s s Human e x t e n d s Object {... @Override p u b l i c String tostring ( ) { r e t u r n "[ Human :... " ; p u b l i c c l a s s Student e x t e n d s Human {... @Override p u b l i c String tostring ( ) { r e t u r n "[ Student :... " ;, /FHTenL, January 11, 2018 25/44

- 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?, /FHTenL, January 11, 2018 26/44

- Example During runtime, the method tostring() from Student will always be used In contrast to the compiler, the runtime environment knows the dynamic type This is called dynamic binding, because the actual type of an object is only determined at runtime The method that is the deepest one in the class hierarchy is chosen, /FHTenL, January 11, 2018 27/44

- Example, Object +tostring() : String Human -name : String -eyecolor : Color +tostring() : String Lecturer -salary : Double Student -snumber : Number +tostring() : String At runtime the method that is most specific is choosen. Although declared 'deepest' in the class hierarchy, it is the first in the list consulted by the jvm. /FHTenL, January 11, 2018 28/44

Exceptions on polymorphism Not all methods are dynamically bound Only overridden methods participate Methods which can t be overridden will bound statically private, static and final methods fall in this category., /FHTenL, January 11, 2018 29/44

Definition Two of the three mandatory components a of a method declaration comprise the method signature the method s name and the parameter types. a A throws clause is possible, but optional can t be instantiated 3 An abstract class can be used as a static (or declaration) type. Useful, for example for classes which are only used as super class, to provide signatures for sub classes The keyword abstract identifies are the opposite of concrete classes Abstract-ness is only about method declarations. Fields cannot be defined abstract. A signature can only occur once in a class defintion, including its inheritance hierarchy. Rationale: In Java all methods can be called ignoring (and thereby NOT declaring) the result. 3 Not even when none of the methods is abstract, /FHTenL, January 11, 2018 30/44

are often used in inheritance They behave like concrete classes A subclass can extend an abstract class and can be abstract itself again p u b l i c a b s t r a c t c l a s s Human {... Human stud1 = new Student ( ) ; Human [ ] humans = new Human [ ] {new Student ( ), new Lecturer ( ) ; Where could be used for as well?, /FHTenL, January 11, 2018 31/44

Abstract methods Methods in could also be abstract They only define a method signature for the sub class Concrete sub classess have to implement these p u b l i c a b s t r a c t c l a s s Human e x t e n d s Object { 1... p r o t e c t e d a b s t r a c t v o i d dress ( ) ; 1 the inheritance from Object is implicit and should normally not be included., /FHTenL, January 11, 2018 32/44

It s difficult to give classes multiple types by using inheritance Inheritance is always done in order, Human inherits from Object, Students inherits from Human, etc. Sometimes, classes need to have types from different hierarchies, Human #name : String #eyecolour : Color +tostring() : String <<Interface>> Callable<T> +call() : T T T Student -snumber : Number +tostring() : String +call() : T Company +call() : Car /FHTenL, January 11, 2018 33/44

Instead of class, interface is used Methods in interfaces don t have a body All methods are automatically abstract and public Constructors are useless and therefore not allowed Instance variables are not allowed either, static-variables however are allowed (automatically final) p u b l i c i n t e r f a c e Callable<T> {, T call ( ) ; /FHTenL, January 11, 2018 34/44

p u b l i c c l a s s Student e x t e n d s Human implements Callable { //... p u b l i c v o i d call ( ) {... p u b l i c c l a s s Student e x t e n d s Human implements Callable, Annoyable { //... p u b l i c v o i d call ( ) {..., p u b l i c StressLevel annoy ( d o u b l e degree ) {... /FHTenL, January 11, 2018 35/44

p u b l i c c l a s s Student e x t e n d s Human implements Callable { //... p u b l i c v o i d call ( ) {... p u b l i c c l a s s Student e x t e n d s Human implements Callable, Annoyable { //... p u b l i c v o i d call ( ) {... p u b l i c StressLevel annoy ( d o u b l e degree ) {..., /FHTenL, January 11, 2018 36/44

Classes can implement multiple interfaces can extend zero, one or multiple other interfaces They allow objects to act in different roles A powerful object can be reduced to a single method Usage analogous to usage of Callable callable = new Student ( ) ; Human human = ( Student ) callable ;, /FHTenL, January 11, 2018 37/44

, What will happen now? /FHTenL, January 11, 2018 38/44

as specification Separation of functionality and implementation Clients communicate implementation-independent Alternative implementations can be used «interface» List T, ArrayList T LinkedList T /FHTenL, January 11, 2018 39/44

vs. p u b l i c i n t e r f a c e Callable<T> { T call ( ) ;, p u b l i c a b s t r a c t c l a s s Callable<T> { a b s t r a c t T call ( ) ; /FHTenL, January 11, 2018 40/44

interfaces: default and static methods To be able to extend of the framework without breaking existing interfaces and implementing classes, Java 8 introduces a few new concepts. static methods (implementations) in interfaces. default method (implementations!) in interfaces., It allows the extension of interfaces without breaking existing implementing classes. The static methods are typically helpers for the default methods. It also implies multiple inheritance for said default methods. If a conflict is possible, the implementation programmer must help the compiler by specifying which default variant method is to be taken. The first use case of this extension is the stream framework, introduced in Java 8, in combination with λ expression. /FHTenL, January 11, 2018 41/44

Multiple inheritance example, parents i n t e r f a c e AnInterface { d e f a u l t String getname ( ) { r e t u r n "An" ; i n t e r f a c e BnInterface { d e f a u l t String getname ( ) { r e t u r n "Bn" ;, /FHTenL, January 11, 2018 42/44

Multiple inheritance example, child i n t e r f a c e CnInterface e x t e n d s AnInterface, BnInterface { // resolve which super to use. // also works in implementing classes @Override d e f a u l t String getname ( ) { r e t u r n AnInterface. s u p e r. getname ( ) ; Note that a class implementing (either 4 ) one of the inherited interfaces-methods with the same signature must also specify which variant to select, using the same construction as above. See DEMO, 4 Because signatur duplication is not allowed, exactly one must be choosen. /FHTenL, January 11, 2018 43/44

Not all understood? For next time read: Java Tutorial on Polymorphims Java 8 tutorial on default methods http://docs.oracle.com/javase/ tutorial/java/iandi/defaultmethods.html Questions? Questions or remarks?, /FHTenL, January 11, 2018 44/44