Inheritance & Polymorphism. Object-Oriented Programming

Similar documents
Object-Oriented Programming

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

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

Java Session. Day 2. Reference: Head First Java

Inheritance & Polymorphism

Object-Oriented Programming More Inheritance

Object-Oriented ProgrammingInheritance & Polymorphism

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

Software Development (cs2500)

Inf1-OOP. Inheritance and Interfaces. Ewan Klein, Perdita Stevens. January 12, School of Informatics

MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

More OO Fundamentals. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 4 09/11/2012

Encapsulation. Inf1-OOP. Getters and Setters. Encapsulation Again. Inheritance Encapsulation and Inheritance. The Object Superclass

Object Fundamentals Part Three. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007

Inheritance, polymorphism, interfaces

Object-Oriented Programming

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

CSA 1019 Imperative and OO Programming

Programmieren II. Polymorphism. Alexander Fraser. June 4, (Based on material from T. Bögel)

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

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

Inheritance (Outsource: )

Lecture 2 and 3: Fundamental Object-Oriented Concepts Kenneth M. Anderson

Programming Using C# QUEEN S UNIVERSITY BELFAST. Practical Week 7

Object Fundamentals Part Three. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 4 09/03/2009

Inheritance and Polymorphism

C09: Interface and Abstract Class and Method

What is Inheritance?

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

OLLSCOIL NA heireann THE NATIONAL UNIVERSITY OF IRELAND, CORK. COLAISTE NA hollscoile, CORCAIGH UNIVERSITY COLLEGE, CORK

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM

C18a: Abstract Class and Method

Object Fundamentals Part Two. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 3 09/01/2009

Inheritance, Polymorphism, and Interfaces

UML & OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 3 08/30/2011

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

Programming using C# LECTURE 07. Inheritance IS-A and HAS-A Relationships Overloading and Overriding Polymorphism

Introduction to Object-Oriented Programming

COMP 250. Lecture 32. polymorphism. Nov. 25, 2016

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

CS1020: DATA STRUCTURES AND ALGORITHMS I

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

Accelerating Information Technology Innovation

Object Orientated Programming Details COMP360

OVERRIDING. 7/11/2015 Budditha Hettige 82

type conversion polymorphism (intro only) Class class

COE318 Lecture Notes Week 9 (Week of Oct 29, 2012)

UML & OO Fundamentals. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 3 09/04/2012

Chapter 14 Abstract Classes and Interfaces

Example: Count of Points

More on Java. Object-Oriented Programming

Java Magistère BFA

Instance Members and Static Members

First IS-A Relationship: Inheritance

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

C10: Garbage Collection and Constructors

COE318 Lecture Notes Week 8 (Oct 24, 2011)

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

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

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

Java Object Oriented Design. CSC207 Fall 2014

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Create a Java project named week10

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Chapter 5. Inheritance

Inheritance. Transitivity

Inheritance & Polymorphism

Introduction to Inheritance

CS-202 Introduction to Object Oriented Programming

About 1. Chapter 1: Getting started with oop 2. Remarks 2. Examples 2. Introduction 2. OOP Introduction 2. Intoduction 2. OOP Terminology 3.

CS111: PROGRAMMING LANGUAGE II

More on Inheritance. Interfaces & Abstract Classes

Interfaces, Polymorphism, and Inheritance

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

C11: Garbage Collection and Constructors

CMSC 132: Object-Oriented Programming II. Inheritance

Interface Class. Lecture 22. Based on Slides of Dr. Norazah Yusof

More Relationships Between Classes

ITI Introduction to Computing II

Inheritance. CSE 142, Summer 2002 Computer Programming 1.

1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code:

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass

Super-Classes and sub-classes

Basic Object-Oriented Concepts. 5-Oct-17

ITI Introduction to Computing II

CSE 11 Final Fall 2009

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

Polymorphism. return a.doublevalue() + b.doublevalue();

INHERITANCE. Spring 2019

CS 61B Discussion 4: Inheritance Fall 2018

CSE 143. "Class Relationships" Class Relationships and Inheritance. A Different Relationship. Has-a vs. Is-a. Hierarchies of Organization

Transcription:

Inheritance & Polymorphism Object-Oriented Programming

Outline Example Design an inheritance structure IS-A and HAS-A Polymorphism protected access level Rules for overriding the Object class Readings: HFJ: Ch. 7. GT: Ch. 7. Đại học Công nghệ - ĐHQG HN Inheritance 2

Inheritance Example 1. Look at what all four classes have in common. 2. They are Shapes, they all rotate and playsound, so we abstract out the common features and put them into a new class called Shape. 3. Then we link all four classes to the new Shape class in a relationship called inheritance. Đại học Công nghệ - ĐHQG HN Inheritance 3

Inheritance Example We read this as Square inherits from Shape. Circle inherits from Shape. Shape is the superclass of Square, Circle, Triangle, Amoeba The other four are subclasses of Shape. if Shape has the functionality, then the subclasses automatically get the same functionality Đại học Công nghệ - ĐHQG HN Inheritance 4

Inheritance Example But Amoeba rotate and playsound differently! 4. Let Amoeba override the inherited rotate() and playsound() Đại học Công nghệ - ĐHQG HN Inheritance 5

Food for thought Tiger HouseCat Which one should be subclass/superclass? Or, should they both be subclasses to some other class? How should you design an inheritance structure? What should be overriden? Đại học Công nghệ - ĐHQG HN Inheritance 6

What is inheritance? The subclass inherits from the superclass, i.e, the subclass inherits members of the superclass: instance variables and methods The subclass specializes the superclass: it can add new variables and methods. it can override inherited methods. Đại học Công nghệ - ĐHQG HN Inheritance 7

Example add a new instance variable add a new method override the inherited method Đại học Công nghệ - ĐHQG HN Inheritance 8

class Animal { String name; void makenoise() { System.out.print("Hmm"); the overriding method class Cow extends Animal { boolean givesmilk; void makenoise() { System.out.print("Moooooooo..."); newly added members class Dog extends Animal { void chasecats() { System.out.print("I'm coming, cat!"); the inherited method Cow cow = new Cow(); cow.makenoise(); cow.givesmilk = true; Dog dog = new Dog(); dog.makenoise(); dog.chasecats(); Đại học Công nghệ - ĐHQG HN Inheritance 9

Design an inheritance structure A program that simulates a number of animals of different species: tigers, lions, wolves, dogs, hippos, cats. We want other programmers to be able to add new kinds of animals to the program at any time. Đại học Công nghệ - ĐHQG HN Inheritance 10

Design an inheritance structure Step 1: Figure out the common abstract characteristics that all animals have. instance variables food hunger location methods makenoise() eat() sleep() roam() Đại học Công nghệ - ĐHQG HN Inheritance 11

Design an inheritance structure Step 2: Design a class that represents all common states and behaviors Đại học Công nghệ - ĐHQG HN Inheritance 12

Design an inheritance structure Step 3: Decide if a subclass needs any behaviours that are specific to that particular subclass Đại học Công nghệ - ĐHQG HN Inheritance 13

Design an inheritance structure Animal Step 4: Look for more inheritance opportunities: Subclasses that might needs common behaviors Feline picture food hunger boundaries location makenoise() eat() sleep() roam() Canine Lion roam() Hippo roam() makenoise() eat() Cat Tiger makenoise() eat() Dog Wolf makenoise() eat() makenoise() eat() makenoise() eat() chasecats() makenoise() eat() Đại học Công nghệ - ĐHQG HN Inheritance 14

Overriding - Which method is called? Which version of the methods get called? Đại học Công nghệ - ĐHQG HN Inheritance 15

IS-A and HAS-A relationship Triangle IS-A Shape Cow IS-An Animal Dog IS-An Animal Inheritance House HAS-A Kitchen Kitchen HAS-A Sink Kitchen HAS-A Stove Composition Đại học Công nghệ - ĐHQG HN Inheritance 16

Code reuse Copy & paste Manually ->Error-prone Composition HAS-A relationship the new class is composed of objects of existing classes. reuse the functionality of the existing class, not its form Inheritance IS-A relationship create a new class as a type of an existing class new class absorbs the existing class's members and extends them with new or modified capabilities Đại học Công nghệ - ĐHQG HN Inheritance 17

protected access level Modifier accessible within same class same package subclasses universe private Yes package (default) Yes Yes protected Yes Yes Yes public Yes Yes Yes Yes Đại học Công nghệ - ĐHQG HN Inheritance 18

protected access level protected members of a superclass are directly accessible from inside its subclasses. public class Person { protected String name; protected String birthday;... public class Employee extends Person { protected int salary; public String tostring() { String s; s = name + "," + birthday; s += "," + salary; return s; Subclass can directly access superclass s protected members Đại học Công nghệ. ĐHQG Hà Nội Inheritance 19

private access level public class Person { private String name; private String birthday; protected String getname(). Private instance variables/methods are not inherited by subclasses public class Employee extends Person { protected int salary; public String tostring() { String s; s = getname() + "," + getbirthday(); s += "," + salary; return s; Đại học Công nghệ. ĐHQG Hà Nội Inheritance 20

Objects and Inheritance Each subclass object figuratively contains a superclass object. Cow object givesmilk Animal object name Therefore In a sense, the subclass object has all superclass object s data, even though it might not inherit them all (remember private members?) In all cases, it should ask the superclass object to initialize its data Đại học Công nghệ - ĐHQG HN Inheritance 21

Object constructors public class Animal { private String name; protected Animal(String _name) {... invokes Animal(_name) public class Cow extends Animal { private boolean givesmilk; public Cow(String _name, boolean _givesmilk) { super(_name);... The call to superclass constructor must be the first statement in subclass constructor Đại học Công nghệ. ĐHQG Hà Nội Inheritance 22

Rules for overriding The principle: the subclass must be able to do anything the superclass declares Therefore, what are the rules for Parameter types? Return types? Method accessability? Đại học Công nghệ - ĐHQG HN Inheritance 23

Overriding parameter types public class Employee { public void f(a x) { public class Manager extends Employee { public void f(b x) { Employee e1, e2; //.. e1.f(x); // x of type A e2.f(x); e2 = new Manager(); // we don t know and don t care // this must work anyway What s the rule for A and B? Đại học Công nghệ. ĐHQG Hà Nội Inheritance 24

Overriding return types public class Employee { public A g() { public class Manager extends Employee { public B g() { Employee e1, e2; //.. e2 = new Manager(); // we don t know and don t care A x = e1.g(); x = e2.g(); // this must work anyway What s the rule for A and B? Đại học Công nghệ. ĐHQG Hà Nội Inheritance 25

Overriding method accessability What s the rule for A and B? public class Employee { public A g() { public class Manager extends Employee { private A g() { Employee e1 = new Employee(); Employee e2 = new Manager(); //.. A x = e1.g(); x = e2.g(); Đại học Công nghệ. ĐHQG Hà Nội Inheritance 26

Rules for overriding The principle: the subclass must be able to do anything the superclass declares Therefore, Parameter types must be the same whatever the superclass takes as an argument, the subclass overriding the method must be able to take that same argument. Return types must be compatible whatever the superclass declares as return type, the subclass must return the same type or a subclass type. The method can't be less accessible a public method cannot be overriden by a private version Đại học Công nghệ - ĐHQG HN Inheritance 27

Wrong overriding Đại học Công nghệ - ĐHQG HN Inheritance 28

What does inheritance buy you? 1. You avoid duplicate code Common features are put in one place 2. You define a common protocol for a group of classes Objects of a subclass are guaranteed to have all features of the superclass. Objects of a subclass can be treated as if they are objects of the superclass. Polymorphism! Đại học Công nghệ - ĐHQG HN Inheritance 29

Polymorphism Normally, Dog dog = new Dog(); With polymorphism: Animal dog = new Dog(); The reference type can be a superclass of the actual object type. Đại học Công nghệ - ĐHQG HN Inheritance 30

Polymorphic arrays An array is declared of type Animal. It can hold objects of Animal's subclasses. Animal[] animals = new Animal[5]; animals[0] = new Dog(); animals[1] = new Cat(); animals[2] = new Wolf(); animals[3] = new Hippo(); animals[4] = new Lion(); we put objects of any subclasses of Animal in the Animal array we can loop through the array and call Animal-class methods, and every object does the right thing! for (int i = 0; i < animals.length; i++) { animals[i].makenoise(); the cat runs Cat's version of makenoise(), the dog runs Dog's version, Đại học Công nghệ - ĐHQG HN Inheritance 31

Polymorphic arguments and return types Parameters of type Animal can take arguments of any subclasses of Animal. it takes arguments of types class Vet { Dog and Cat public void giveshot(animal a) { // give a a shot, vaccination for example a.makenoise(); Vet v = new Vet(); Dog d = new Dog(); Cat c = new Cat(); v.giveshot(d); v.giveshot(c); the Dog's makenoise() is invoked the Cat's makenoise() is invoked Đại học Công nghệ - ĐHQG HN Inheritance 32

class Animal { String name;... public void makenoise() { System.out.print ("Hmm."); public void introduce() { makenoise(); System.out.println(" I'm " + name); class Cat extends Animal {... public void makenoise() { System.out.print("Meow..."); class Cow extends Animal {... public void makenoise() { System.out.print("Moo..."); Polymorphism: The same message "makenoise" is interpreted differently, depending on the type of the owner object Animal pet1 = new Cat("Tom Cat"); Animal pet2 = new Cow("Mini Cow"); pet1.introduce(); pet2.introduce(); Meow... I'm Tom Cat Moo... I'm Mini Cow Đại học Công nghệ - ĐHQG HN Inheritance 33

What is polymorphism? Polymorphism: exist in many forms Object polymorphism: Objects of subclasses can be treated as if they are all objects of the superclass. A Dog object can be seen as an Animal object as well Even when treated uniformly, objects of different subclasses interpret the same message differently ananimal.makenoise() works differently depending on what kind of Animal ananimal is currently refering to. Đại học Công nghệ - ĐHQG HN Inheritance 34

What polymorphism buy you? With polymorphism, you can write code that doesn't have to change when you introduce new subclass types into the program Animal[] animals = new Animal[5];... for (int i = 0; i < animals.length; i++) { animals[i].makenoise(); class Vet { public void giveshot(animal a) { // give a a shot, vaccination for example a.makenoise(); Đại học Công nghệ - ĐHQG HN Inheritance 35

class Animal {... public void makenoise() { System.out.print ("Hmm."); public void introduce() { makenoise(); System.out.println(" I'm " + name); Cat - name Animal + makenoise() + introduce() Cow Duck class Pig extends Animal { public void makenoise() { System.out.print("Oi oi..."); + makenoise() + makenoise() class Duck extends Animal { public void makenoise() { System.out.print("Quack quack..."); You can add as many new animal types as you want without having to modify the introduce() method! + makenoise() Separate things that change from things that stay the same Đại học Công nghệ - ĐHQG HN Inheritance 36

Object class All classes are subclasses to the class Object inherited methods: Class getclass() int hashcode() boolean equals() String tostring() Car c1 = new Car(); Car c2 = new Car(); equals() and tostring() should be overriden to work properly Object equals() getclass() hashcode() tostring() speed Car accelerate() decelerate() System.out.println(c1.equals(c2)); System.out.println(c1.getClass() + c1.hashcode()); System.out.println(c1.toString() + "," + c2); Đại học Công nghệ - ĐHQG HN Inheritance 37