Inheritance in Java. Produced by: Eamonn de Leastar Dr. Siobhán Drohan

Similar documents
Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Object Oriented Concepts. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Java Control Statements

Java Overview An introduction to the Java Programming Language

More on Abstraction in Java

Java Object Oriented Design. CSC207 Fall 2014

Rules and syntax for inheritance. The boring stuff

Chapter 14 Abstract Classes and Interfaces

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

What is Inheritance?

Chapter 10 Classes Continued. Fundamentals of Java

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

Practice for Chapter 11

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance. Exploring Polymorphism. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

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. Java-Lecture 11 Polymorphism

1 Shyam sir JAVA Notes

Inheritance. A key OOP concept

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Programming II (CS300)

Introduction to Programming Using Java (98-388)

More Relationships Between Classes

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

Abstract Classes and Interfaces

Inheritance and Polymorphism

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

Inheritance (continued) Inheritance

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

C++ Inheritance and Encapsulation

Inheritance and Interfaces

Chapter 5 Object-Oriented Programming

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

ITI Introduction to Computing II

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Lecture 18 CSE11 Fall 2013 Inheritance

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

CMSC 132: Object-Oriented Programming II

ITI Introduction to Computing II

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

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

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Java Magistère BFA

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

More about inheritance

CSC9T4: Object Modelling, principles of OO design and implementation

Inheritance and Polymorphism

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

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

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

Inheritance -- Introduction

CS Programming I: Inheritance

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

CS-202 Introduction to Object Oriented Programming

Annotations in Java (JUnit)

INHERITANCE AND EXTENDING CLASSES

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

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

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

Java Fundamentals (II)

Inheritance Motivation

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

CS 251 Intermediate Programming Inheritance

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

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

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

COP 3330 Final Exam Review

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

INHERITANCE. Spring 2019

C++ Inheritance and Encapsulation

Chapter 6 Introduction to Defining Classes

Making New instances of Classes

Inheritance. Transitivity

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Chapter 5. Inheritance

Inheritance and Polymorphism in Java

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Type Hierarchy. Lecture 6: OOP, autumn 2003

COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

OVERRIDING. 7/11/2015 Budditha Hettige 82

Object Oriented Programming: Based on slides from Skrien Chapter 2

C++ Important Questions with Answers

Collections, Maps and Generics

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Super-Classes and sub-classes

Fast Track to Core Java 8 Programming for OO Developers (TT2101-J8) Day(s): 3. Course Code: GK1965. Overview

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

25. Interfaces. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Inheritance, Polymorphism, and Interfaces

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

First IS-A Relationship: Inheritance

Inheritance and Polymorphism. CS180 Fall 2007

Algorithms. Produced by. Eamonn de Leastar

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

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

Programming II (CS300)

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

Transcription:

Inheritance in Java Produced by: Eamonn de Leastar (edeleastar@wit.ie) Dr. Siobhán Drohan (sdrohan@wit.ie) Department of Computing and Mathematics http://www.wit.ie/

Essential Java Overview Introduction Syntax Basics Arrays Classes Classes Structure Static Members Commonly used Classes Control Statements Control Statement Types If, else, switch For, while, do-while Inheritance Class hierarchies Method lookup in Java Use of this and super Constructors and inheritance Abstract classes and methods Interfaces Collections ArrayList HashMap Iterator Vector Enumeration Hashtable Exceptions Exception types Exception Hierarchy Catching exceptions Throwing exceptions Defining exceptions Common exceptions and errors Streams Stream types Character streams Byte streams Filter streams Object Serialization 3

Overview: Road Map What is inheritance? Implementation Inheritance Method lookup in Java Use of this and super Constructors and inheritance Abstract classes and methods Interface Inheritance Definition Implementation Type casting Naming Conventions 2

What is Inheritance? Inheritance is one of the primary object-oriented principles. It is a mechanism for sharing commonalities between classes. 3

Two types of Inheritance: What is Inheritance? 1. Implementation Inheritance It promotes reuse Commonalities are stored in a parent class - called the superclass Commonalities are shared between children classes - called the subclasses 2. Interface Inheritance Mechanism for introducing Types into java design Classes can support more than one interface, i.e. be of more than one type 3

Implementation Inheritance Policy client premium policynumber HomePolicy house getclient setclient AutoPolicy auto LifePolicy specialization gethouse sethouse getauto setauto 4

Defining Inheritance In Java, inheritance is supported by using keyword extends It is said that a subclass extends a superclass. If the class definition does not specify explicit superclass, its superclass is Object class. public class Policy { public class HomePolicy extends Policy{ public class AutoPolicy extends Policy{ public class LifePolicy extends Policy{ public class Policy{ public class Policy extends Object{ 5

Variables and Inheritance Variables can be declared against the superclass, and assigned objects of the subclass. e.g. Variable declared as of type Policy can be assigned an instance of any Policy s subclasses. Policy policy; policy = new Policy(); Policy policy; policy = new HomePolicy(); Policy policy; policy = new AutoPolicy(); Policy policy; policy = new LifePolicy(); 6

Multiple Inheritance Not supported in Java A class cannot extend more than one class There is only one direct superclass for any class Object class is exception as it does not have superclass Any idea why the Java designers decided to not allow multiple inheritance? 7

Deadly Diamond of Death Let s pretend that Java allows multiple inheritance and we will see really quickly what the Deadly Diamond of Death is! Suppose that we have an abstract super class, with an abstract method in it. public abstract class AbstractSuperClass{ abstract void do(); http://javacodeonline.blogspot.ie/2009/08/deadly-diamond-of-death.html

Deadly Diamond of Death Now two concrete classes extend this abstract super class. Each classes provides their own implementation of the abstract method defined in the super class. public class ConcreteOne extends AbstractSuperClass{ void do(){ System.out.println("I am testing multiple Inheritance"); public class ConcreteTwo extends AbstractSuperClass{ void do(){ System.out.println("I will cause the Deadly Diamond of Death"); http://javacodeonline.blogspot.ie/2009/08/deadly-diamond-of-death.html

Deadly Diamond of Death So far, our class diagram looks like this: <<abstract>> AbstractSuperClass ConcreteOne ConcreteTwo http://javacodeonline.blogspot.ie/2009/08/deadly-diamond-of-death.html

Deadly Diamond of Death Now, if multiple inheritance were allowed, a fourth class comes into picture which extends the above two concrete classes. public class DiamondEffect extends ConcreteOne, ConcreteTwo{ //Some methods of this class http://javacodeonline.blogspot.ie/2009/08/deadly-diamond-of-death.html

Deadly Diamond of Death Note that our class diagram is a diamond shape. <<abstract>> AbstractSuperClass ConcreteOne ConcreteTwo DiamondEffect http://javacodeonline.blogspot.ie/2009/08/deadly-diamond-of-death.html

Deadly Diamond of Death The DiamondEffect class inherits all the methods of the parent classes. BUT we have a common method (void do()) in the two concrete classes, each with a different implementation. So which void do() implementation will be used for the DiamondEffect class as it inherits both these classes? ConcreteOne <<abstract>> AbstractSuperClass DiamondEffect ConcreteTwo http://javacodeonline.blogspot.ie/2009/08/deadly-diamond-of-death.html

Deadly Diamond of Death Actually no one has got the answer to the above question so to avoid this sort of critical issue, Java banned multiple inheritance. http://javacodeonline.blogspot.ie/2009/08/deadly-diamond-of-death.html

What is Inherited? In general all subclasses inherit from superclass: Data Behavior When we map these to Java it means that subclasses inherit: Fields (instance variables) Methods 8

Inheriting Fields All fields from superclasses are inherited by a subclass. Inheritance goes all the way up the hierarchy. client premium policynumber Policy client premium policynumber house HomePolicy client premium policynumber house 9

Inheriting Methods All methods from superclasses are inherited by a subclass Inheritance goes all the way up the hierarchy getclient setclient getpremium setpremium getpolicynumber setpolicynumber Policy getclient setclient getpremium setpremium getpolicynumber setpolicynumber gethouse sethouse HomePolicy getclient setclient getpremium setpremium getpolicynumber setpolicynumber gethouse sethouse 10

Overview: Road Map What is inheritance? Implementation Inheritance Method lookup in Java Use of this and super Constructors and inheritance Abstract classes and methods Interface Inheritance Definition Implementation Type casting Naming Conventions 2

Method Lookup HomePolicy homepolicy = new HomePolicy(); homepolicy.getpremium(); Method lookup begins in the class of that object that receives a message Policy class method found Policy premium getpremium setpremium If method is not found lookup continues in the superclass HomePolicy class method not found HomePolicy house gethouse sethouse 11

this vs. super They are both names of the receiver object The difference is where the method lookup begins: this Lookup begins in the receiver object s class super Lookup begins in the superclass of the class where the method is defined getclass() Method in java.lang.object. It returns the runtime class of the receiver object. getclass().getname() Method in java.lang.class. It returns the name of the class or interface of the receiver object. 12

class Policy { // public void print() { System.out.println("A " + getclass().getname() + ", $" + getpremium()); //.. Policy p = new Policy(); p.print(); A Policy, $1,200.00 class HomePolicy extends Policy { // public void print() { super.print(); System.out.println("for house " + gethouse().tostring(); // Policy HomePolicy HomePolicy h = new HomePolicy(); h.print(); A HomePolicy, $1,200.00 for house 200 Great Street 13

Method Overriding If a class defines the same method as its superclass, it is said that the method is overridden Method signatures must match Policy HomePolicy //Method in the Policy class public void print() { System.out.println("A " + getclass().getname() + ", $" + getpremium()); //Overridden method in the HomePolicy class public void print() { super.print(); System.out.println("for house " + gethouse().tostring(); 14

Overview: Road Map What is inheritance? Implementation Inheritance Method lookup in Java Use of this and super Constructors and inheritance Abstract classes and methods Interface Inheritance Definition Implementation Type casting Naming Conventions 2

Constructors and Inheritance Constructors are not inherited by the subclasses. The first line in the subclass constructor must be a call to the superclass constructor. If the call is not coded explicitly then an implicit zeroargument super() is called. If the superclass does not have a zero-argument constructor, this causes an error. Adopting this approach eventually leads to the Object class constructor that creates the object. 15

Constructors and Inheritance public Policy(double premium, Client aclient, String policynumber) { this.premium = premium; this.policynumber = policynumber; this.client = aclient; Policy HomePolicy public HomePolicy(double premium, Client aclient, String policynumber, House ahouse) { super(premium, aclient, policynumber); this.house = ahouse; 16

Overview: Road Map What is inheritance? Implementation Inheritance Method lookup in Java Use of this and super Constructors and inheritance Abstract classes and methods Interface Inheritance Definition Implementation Type casting Naming Conventions 2

Abstract vs Concrete Abstract Implementation delayed abstract method has no code cannot instantiate an abstract class (it has, by definition unfinished methods) Concrete All code is complete.

Abstract Classes An abstract class is a class that contains zero or more abstract methods. An class that has an abstract method must be declared abstract. Abstract classes cannot be instantiated. Abstract classes function as a base for subclasses. abstract classes can be subclassed. Concrete subclasses complete the implementation.

Defining Abstract Classes Modifier abstract is used to indicate abstract class public abstract class Policy { Policy HomePolicy AutoPolicy LifePolicy 18

Abstract Methods Can only be defined in abstract classes Abstract classes can contain concrete methods as well. Declaration of abstract method in concrete class will result in compile error; any class with an abstract method has to be declared abstract. Abstract classes are not required to have abstract methods. Declare method signatures Implementation is left to the subclasess. Each subclass must have concrete implementation of the abstract method(s) Used to impose method implementation on subclasses 19

Defining Abstract Methods Modifier abstract is also used to indicate abstract method public abstract class Policy { public abstract void calculatefullpremium(); Policy calculatefullpremium HomePolicy AutoPolicy LifePolicy 20

Defining Abstract Methods All subclasses must implement all abstract methods public class HomePolicy extends Policy { // public void calculatefullpremium() { //calculation may depend on a criteria about the house public class AutoPolicy extends Policy { // public void calculatefullpremium() { //calculation may depend on a criteria about the auto public class LifePolicy extends Policy { // public void calculatefullpremium() { //calculation may depend on a criteria about the client 21

Overview: Road Map What is inheritance? Implementation Inheritance Method lookup in Java Use of this and super Constructors and inheritance Abstract classes and methods Interface Inheritance Definition Implementation Type casting Naming Conventions 2

Interfaces We know why multiple inheritance is not allowed in Java.Deadly Diamond of Death. However, there is a way to simulate multiple inheritance. interfaces can be used when you can see a multiple inheritance in your class design.

What is an interface? Writing an interface is similar to writing a class. But a class describes the attributes and behaviours of an object. And an interface contains behaviours that a class implements. http://www.tutorialspoint.com/java/java_interfaces.htm

What is an interface? An interface is: a type in Java similar(ish) to a class, a collection of abstract method signatures. http://www.tutorialspoint.com/java/java_interfaces.htm

What is an interface? Along with abstract methods an interface may also contain: constants i.e. final static fields default methods static methods Method bodies exist only for default methods and static methods. NOTE: Pre Java 8, Interfaces did not have static and default methods. http://www.tutorialspoint.com/java/java_interfaces.htm

Interface Rules Summary Interfaces can contain: Only method signatures for abstract methods. Only final static fields. default and static methods (including their implementation). Interfaces cannot contain: Any fields other than public final static fields. Any constructors. Any concrete methods, other than default and static ones. 26

Defining Interfaces abstract methods Similar to defining classes Keyword interface used instead of class keyword Defined abstract methods contain signatures only (no need for keyword abstract) Interfaces are also stored in.java files public interface IAddressBook { void clear(); IContact getcontact(string lastname); void addcontact(icontact contact); int numberofcontacts(); void removecontact(string lastname); String listcontacts(); Methods are implicitly public access. 24

Defining Interfaces default methods Pre Java 8, adding a new method to an Interface breaks all classes that extend the Interface. Java 8 introduced default methods as a way to extend Interfaces in a backward compatible way. They allow you to add new methods to Interfaces without breaking existing implementations of those Interfaces. Default method uses the default keyword and is implicitly public access. public interface IAddressBook { void clear(); IContact getcontact(string lastname); void addcontact(icontact contact); int numberofcontacts(); void removecontact(string lastname); String listcontacts(); default void typeofentity(){ System.out.println( Address book ); 24

Defining Interfaces static methods In addition to default methods, Java 8 allows you to add static methods to Interfaces. Use the static keyword at the beginning of the method signature. All method declarations in an interface, including static methods, are implicitly public, so you can omit the public modifier. public interface IAddressBook { static final int CAPACITY= 1000; void clear(); IContact getcontact(string lastname); void addcontact(icontact contact); int numberofcontacts(); void removecontact(string lastname); String listcontacts(); default void typeofentity(){ System.out.println( Address book ); static int getcapacity(){ return CAPACITY; 24

Overview: Road Map What is inheritance? Implementation Inheritance Method lookup in Java Use of this and super Constructors and inheritance Abstract classes and methods Interface Inheritance Definition Implementation Type casting Naming Conventions 2

Implementing an Interface When a class implements an interface: you can think of the class as signing a contract, agreeing to perform the specific behaviours of the interface. If a class does not perform all the behaviours of the interface, the class must declare itself as abstract. http://www.tutorialspoint.com/java/java_interfaces.htm

Implementing Interfaces Classes implement Interfaces. Keyword implements is used. Implementing classes are subtypes of the interface type. They must define all abstract methods for the Interface(s) they implement. public class AddressBook implements IAddressBook { private Contact[] contacts; private int nmrcontacts; public AddressBook() { contacts = new Contact[IAddressBook.getCapacity()]; nmrcontacts = 0; private int locateindex(string lastname) { // public void clear() { // //... 25

Implementing an Interface: Rules When implementing interfaces there are several rules: A class can implement more than one interface at a time i.e. have more than one type. A class can extend only one class, but implement many interfaces. An interface can extend another interface, similarly to the way that a class can extend another class. An interface cannot implement another interface. http://www.tutorialspoint.com/java/java_interfaces.htm

Interfaces can be Inherited It is possible that one interface extends other interfaces Sometimes known as subtyping Multiple inheritance is allowed with interfaces; whereas a class can extend only one other class, an interface can extend any number of interfaces. Inheritance works the same as with classes All methods defined are inherited. 30

Extending Interfaces public interface Car { public double getspeed(); <<interface> Car public interface Color { public String getbasecolor(); <<interface> Color <<interface> ColoredCar public interface ColoredCar extends Car, Color { public String gofaster(); 31

Interfaces in Collections Framework

Interfaces in Collections Framework ArrayList implements the List interface. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface. Applying this rule to a List: List<Product> products = new ArrayList<Product>();

Overview: Road Map What is inheritance? Implementation Inheritance Method lookup in Java Use of this and super Constructors and inheritance Abstract classes and methods Interface Inheritance Definition Implementation Type casting Naming Conventions 2

Reference vs Interface type Variables can be declared as: Reference type Any instance of that class or any of the subclasses can be assigned to the variable. Policy policy; policy = new Policy(); Policy policy; policy = new HomePolicy(); Interface type Any instance of any class that implements that interface can be assigned to the variable. IAddressBook book; book = new AddressBook(); book.clear(); book.addcontact(contact); // etc book declared as an IAddressBook interface type 27

Variables and Messages If a variable is defined as a certain type, only messages defined for that type can be sent to the variable. IAddressBook book; book = new AddressBook(); book.clear(); book.addcontact(contact); int i = book.locateindex( mike ); // Error! // // static type is IAddressBook // compile-time check finds that // locateindex() is defined in // AddressBook but not in // IAddressBook. 28

Type Casting Type casting can be subverted (undermined) by type checking. To be used rarely and with care. Type cast can fail, and run time error will be generated if the book object really is not an AddressBook (e.g. it could be an AddressBookMap which also implements IAddressBook) IAddressBook book; book = new AddressBook(); book.clear(); book.addcontact(contact); int i = ((AddressBook)book).locateIndex( mike ); Type cast from IAddressBook to AddressBook 29

Common Naming Conventions There are a few conventions when naming interfaces: Suffix able is often used for interfaces Cloneable, Serializable, and Transferable Nouns are often used for implementing classes names, and I + noun for interfaces Interfaces: IColor, ICar, and IColoredCar Classes: Color, Car, and ColoredCar Nouns are often used for interfaces names, and noun+impl for implementing classes Interfaces: Color, Car, and ColoredCar Classes: ColorImpl, CarImpl, and ColoredCarImpl 32

Review What is inheritance? Implementation Inheritance Method lookup in Java Use of this and super Constructors and inheritance Abstract classes and methods Interface Inheritance Definition Implementation Type casting Naming Conventions 33

Except where otherwise noted, this content is licensed under a Creative Commons Attribution-NonCommercial 3.0 License. For more information, please see http://creativecommons.org/licenses/by-nc/3.0/