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

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

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

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

CS 251 Intermediate Programming Inheritance

What is Inheritance?

Object Oriented Programming. Java-Lecture 11 Polymorphism

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

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

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

Java Object Oriented Design. CSC207 Fall 2014

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

Inheritance -- Introduction

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

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.

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

CS111: PROGRAMMING LANGUAGE II

Chapter 5. Inheritance

Lecture 18 CSE11 Fall 2013 Inheritance

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

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

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

CS-202 Introduction to Object Oriented Programming

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

Inheritance (continued) Inheritance

Inheritance and Polymorphism

C++ Important Questions with Answers

Programming II (CS300)

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

Practice for Chapter 11

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

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

Inheritance (Outsource: )

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

Inheritance. Transitivity

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

25. Generic Programming

Class, Variable, Constructor, Object, Method Questions

1 Shyam sir JAVA Notes

More Relationships Between Classes

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

CS111: PROGRAMMING LANGUAGE II

Inheritance and Polymorphism

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

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

OVERRIDING. 7/11/2015 Budditha Hettige 82

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

Inheritance and Polymorphism. CS180 Fall 2007

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

Inheritance and Polymorphism

First IS-A Relationship: Inheritance

Chapter 14 Abstract Classes and Interfaces

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

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

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

Inheritance and Polymorphism

Declarations and Access Control SCJP tips

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

Java: introduction to object-oriented features

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

Inheritance, Polymorphism, and Interfaces

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

Classes and Inheritance Extending Classes, Chapter 5.2

CS Programming I: Inheritance

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

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

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

Pieter van den Hombergh. Fontys Hogeschool voor Techniek en Logistiek. September 9, 2016

Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright

CMSC 132: Object-Oriented Programming II

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

ITI Introduction to Computing II

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

Unit 4 - Inheritance, Packages & Interfaces

PROGRAMMING LANGUAGE 2

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

COMP 110/L Lecture 19. Kyle Dewey

Inheritance and Polymorphism

Chapter 6 Introduction to Defining Classes

Programming II (CS300)

Week 7 Inheritance. Written by Alexandros Evangelidis. Adapted from Joseph Gardiner. 10 November 2015

[ L5P1] Object-Oriented Programming: Advanced Concepts

ITI Introduction to Computing II

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

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

Java Fundamentals (II)

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

CS111: PROGRAMMING LANGUAGE II

Rules and syntax for inheritance. The boring stuff

Example: Count of Points

Example: Count of Points

INHERITANCE. Spring 2019

Lecture 2: Java & Javadoc

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Transcription:

Inheritance and Inheritance and Pieter van den Hombergh Thijs Dorssers Stefan Sobek Fontys Hogeschool voor Techniek en Logistiek February 10, 2017 /FHTenL Inheritance and February 10, 2017 1/45

Topics Class hierarchy - An example Inheritance and I can see what you can t and inheritance /FHTenL Inheritance and February 10, 2017 2/45

Known Between objects, relationships exist Inheritance and /FHTenL Inheritance and February 10, 2017 3/45

Known Between objects, relationships exist An association represents a Has-relationship A human being has two legs A chair has 4 chair legs A car has 4 wheels Inheritance and /FHTenL Inheritance and February 10, 2017 3/45

Known Between objects, relationships exist An association represents a Has-relationship A human being has two legs A chair has 4 chair legs A car has 4 wheels Beside, a Is-a-relationship exists Apples and pears are fruit species Students and lecturers are humans The type defines characteristics for its elements Each human being has an eye color Each human being has a hair color Each human being has a size Java represents this relationship by inheritance Parents give their Childs characteristics Inheritance and /FHTenL Inheritance and February 10, 2017 3/45

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

The implicit base class Object Classes without the extends-keyword automatically inherit from Object Object is an implicit super class Each class inherits either directly or indirectly from java.lang.object All visible attributes and methods, like tostring(), are inherited Inheritance and /FHTenL Inheritance and February 10, 2017 5/45

No Multiple inheritance in Java Java only allows single inheritance Behind the extends-keyword, only one super class is allowed ao C++, Python and Perl allow Multiple Inheritance. Why does java not? Inheritance and new SubClass().doSomething(); Do what??? /FHTenL Inheritance and February 10, 2017 6/45

Example Person Inheritance and 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 February 10, 2017 7/45

Example Human package nl. fontys. pro2. week1 ; import java. awt. Color ; public class Human { protected String name ; protected Color eyecolor ; Inheritance and package nl. fontys. pro2. week1 ; public class Student extends Human { private Number number ; /FHTenL Inheritance and February 10, 2017 8/45

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

:I can see what you can t Inheritance and /FHTenL Inheritance and February 10, 2017 10/45

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 and methods are inherited by all sub classes are visible for all classes in the same package public protected package-private private Protected -protection is weaker than package-private! Inheritance and /FHTenL Inheritance and February 10, 2017 11/45

table Inheritance and Table: Normalized visibility table. Modifier Class Package Subclass World public y y y y protected y y y - (default) y y - - private y - - - /FHTenL Inheritance and February 10, 2017 12/45

Usage of constructors with inheritance 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 constructor When no constructor has explicitly been defined, the implicit default constructor is used Inheritance and /FHTenL Inheritance and February 10, 2017 13/45

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 public class Student extends Human { public Student ( Number number ){... public class StudAssistant extends Student { public StudAssistant ( Number snumber ){ super ( snumber ); /FHTenL Inheritance and February 10, 2017 14/45

Summary constructors and methods can t be abstract, final, native, static or synchronized don t have a return value, even not void are not inherited Can have all 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 /FHTenL Inheritance and February 10, 2017 15/45

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: Inheritance and Human studentishuman = new Student (); Human lecturerishuman = new Lecturer (); Object humanisobject = new Human (); Student studentisstudent = new Student (); /FHTenL Inheritance and February 10, 2017 16/45

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 Inheritance and Human studhum = new Student (); System. out. println ( studhum. getname ()); // The following will not work : System. out. println ( studhum. getsnumber ()); /FHTenL Inheritance and February 10, 2017 17/45

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 Inheritance and 1 less specific /FHTenL Inheritance and February 10, 2017 18/45

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

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. Inheritance and public class Student extends Human {... @Override public void setname ( String name ) { if( isnicename ( name )){ super. setname ( name ); /FHTenL Inheritance and February 10, 2017 20/45

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? Inheritance and 2 Defined in this way in java.lang.object /FHTenL Inheritance and February 10, 2017 21/45

Not all understood? For next time read: Introduction to Java Programming: Chapter 11 Questions? Questions or remarks? Inheritance and /FHTenL Inheritance and February 10, 2017 22/45

, abstract classes and interfaces, abstract classes and interfaces Abstract classes and methods Java8 Pieter van den Hombergh Thijs Dorssers Stefan Sobek multiple I. Parents Children Fontys Hogeschool voor Techniek en Logistiek February 10, 2017 /FHTenL, abstract classes and interfaces February 10, 2017 23/45

Topics Abstract classes and methods, abstract classes and interfaces Abstract classes and methods Java8 interfaces: default and static Java8 multiple I. Parents Children multiple inheritance of implementation Example: Parents Example: Child interfaces /FHTenL, abstract classes and interfaces February 10, 2017 24/45

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, abstract classes and interfaces Abstract classes and methods Java8 multiple I. Parents Children /FHTenL, abstract classes and interfaces February 10, 2017 25/45

- Example public class Human extends Object {... @Override public String tostring (){ return "[ Human :... "; public class Student extends Human {... @Override public String tostring (){ return "[ Student :... ";, abstract classes and interfaces Abstract classes and methods Java8 multiple I. Parents Children /FHTenL, abstract classes and interfaces February 10, 2017 26/45

- 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?, abstract classes and interfaces Abstract classes and methods Java8 multiple I. Parents Children /FHTenL, abstract classes and interfaces February 10, 2017 27/45

- 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, abstract classes and interfaces Abstract classes and methods Java8 multiple I. Parents Children /FHTenL, abstract classes and interfaces February 10, 2017 28/45

- Example Object +tostring() : String, abstract classes and interfaces Abstract classes and methods Human -name : String -eyecolor : Color +tostring() : String Java8 multiple I. Parents Children 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, abstract classes and interfaces February 10, 2017 29/45

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., abstract classes and interfaces Abstract classes and methods Java8 multiple I. Parents Children /FHTenL, abstract classes and interfaces February 10, 2017 30/45

Abstract classes Abstract classes can t be instantiated 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 abstract classes Abstract classes are the opposite of concrete classes, abstract classes and interfaces Abstract classes and methods Java8 multiple I. Parents Children public abstract class Human {... /FHTenL, abstract classes and interfaces February 10, 2017 31/45

Abstract classes Abstract classes are often used in inheritance They behave like concrete classes A subclass can extend an abstract class and can be abstract itself again Human stud1 = new Student (); Human [] humans = new Human [] { new Student (), new Lecturer () ;, abstract classes and interfaces Abstract classes and methods Java8 multiple I. Parents Children Where could abstract classes be used for as well? /FHTenL, abstract classes and interfaces February 10, 2017 32/45

Abstract methods Methods in abstract classes could also be abstract They only define a method signature for the sub class Concrete sub classess have to implement these, abstract classes and interfaces Abstract classes and methods public abstract class Human extends Object {... protected abstract void dress (); Java8 multiple I. Parents Children /FHTenL, abstract classes and interfaces February 10, 2017 33/45

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, abstract classes and interfaces Abstract classes and methods Java8 multiple I. Human #name : String #eyecolour : Color +tostring() : String <<Interface>> Callable<T> +call() : T T Parents Children T Student -snumber : Number +tostring() : String +call() : T Company +call() : Car /FHTenL, abstract classes and interfaces February 10, 2017 34/45

Instead of class, interface is used Methods in interfaces don t have a body All methods are automatically abstract and public are useless and therefore not allowed Instance variables are not allowed either, static-variables however are allowed (automatically final), abstract classes and interfaces Abstract classes and methods Java8 multiple I. Parents Children public interface Callable <T > { T call (); /FHTenL, abstract classes and interfaces February 10, 2017 35/45

public class Student extends Human implements Callable { //... public void call () {..., abstract classes and interfaces Abstract classes and methods public class Student extends Human implements Callable, Annoyable { //... Java8 multiple I. Parents Children public void call () {... public StressLevel annoy ( double degree ) {... /FHTenL, abstract classes and interfaces February 10, 2017 36/45

public class Student extends Human implements Callable { //... public void call () {... public class Student extends Human implements Callable, Annoyable { //... public void call () {..., abstract classes and interfaces Abstract classes and methods Java8 multiple I. Parents Children public StressLevel annoy ( double degree ) {... /FHTenL, abstract classes and interfaces February 10, 2017 37/45

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 abstract classes, abstract classes and interfaces Abstract classes and methods Java8 multiple I. Parents Children Callable callable = new Student (); Human human = ( Student ) callable ; /FHTenL, abstract classes and interfaces February 10, 2017 38/45

, abstract classes and interfaces Abstract classes and methods Java8 multiple I. Parents Children What will happen now? /FHTenL, abstract classes and interfaces February 10, 2017 39/45

as specification Separation of functionality and implementation Clients communicate implementation-independent Alternative implementations can be used, abstract classes and interfaces Abstract classes and methods «interface» List T Java8 multiple I. Parents Children ArrayList T LinkedList T /FHTenL, abstract classes and interfaces February 10, 2017 40/45

vs. Abstract classes public interface Callable <T > { T call ();, abstract classes and interfaces Abstract classes and methods Java8 public abstract class Callable <T > { abstract T call (); multiple I. Parents Children /FHTenL, abstract classes and interfaces February 10, 2017 41/45

Java8 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., abstract classes and interfaces Abstract classes and methods Java8 multiple I. /FHTenL, abstract classes and interfaces February 10, 2017 42/45 Parents Children

Multiple inheritance example, parents interface AnInterface { default String getname () { return "An"; interface BnInterface { default String getname () { return "Bn";, abstract classes and interfaces Abstract classes and methods Java8 multiple I. Parents Children /FHTenL, abstract classes and interfaces February 10, 2017 43/45

Multiple inheritance example, child interface CnInterface extends AnInterface, BnInterface { // resolve which super to use. // also works in implementing classes @Override default String getname () { return AnInterface. super. getname ();, abstract classes and interfaces Abstract classes and methods Java8 multiple I. Parents Children Note that a class implementing two interfaces-methods with the same signature must also specify which variant to select, using the same construction as above. See DEMO /FHTenL, abstract classes and interfaces February 10, 2017 44/45

Any open issues? Not all understood? For next time read: Introduction to Java Programming: Chapter 11 Java 8 tutorial on default methods http://docs.oracle.com/javase/tutorial/java/ IandI/defaultmethods.html Questions? Questions or remarks?, abstract classes and interfaces Abstract classes and methods Java8 multiple I. Parents Children /FHTenL, abstract classes and interfaces February 10, 2017 45/45