Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Objects First With Java A Practical Introduction Using BlueJ Improving structure with inheritance 2.0.
Improving structure with inheritance Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main concepts.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
Java Inheritance. What is inherited A subclass inherits variables and methods from its superclass and all of its ancestors. The subclass can use these.
Chapter 8 Improving Structure with Inheritance. The DoME Example The Database of Multimedia Entertainment We will be storing information about CDs and.
23-May-15 Polymorphism. 2 Signatures In any programming language, a signature is what distinguishes one function or method from another In C, every function.
Polymorphism & Methods COMP204 Bernhard Pfahringer (with lots of input from Mark Hall) poly + morphos (greek) “many forms”
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Improving structure with inheritance (Chapters 8 and 9)
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
Inheritance Chapter 8.
More about inheritance Exploring polymorphism. 02/12/2004Lecture 8: More about inheritance2 Main concepts to be covered method polymorphism static and.
CPSC150 Inheritance Details Chapter 9. CPSC150 Print in Entertainment ver 2 (with inheritance): public void print() { System.out.print("title: " + title.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
More about inheritance Exploring polymorphism 5.0.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
Abstract Classes and Interfaces
More about inheritance Exploring polymorphism 3.0.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Programming Fundamentals 2: Inheritance/ F II Objectives – –the use of super, overriding, method polymorphism (dynamic binding), protected.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
What is inheritance? It is the ability to create a new class from an existing class.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Object-Oriented Programming. An object is anything that can be represented by data in a computer’s memory and manipulated by a computer program.
28-Dec-04polymorhism.ppt1 Polymorphism. 28-Dec-04polymorhism.ppt2 signatures in any programming language, a signature is what distinguishes one function.
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
OOP: Encapsulation,Abstraction & Polymorphism. What is Encapsulation Described as a protective barrier that prevents the code and data being randomly.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
More about inheritance Exploring polymorphism 5.0.
Inheritance and Access Control CS 162 (Summer 2009)
CET203 SOFTWARE DEVELOPMENT Session 2B Constructors, Overriding and Overloading.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Comp1004: Inheritance I Super and Sub-classes. Coming up Inheritance and Code Duplication – Super and sub-classes – Inheritance hierarchies Inheritance.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Polymorphism & Methods COMP206 Geoff Holmes & Bernhard Pfahringer (these slides: lots of input from Mark Hall) poly + morphos (greek) “many forms”
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
CS 106 Introduction to Computer Science I 04 / 18 / 2008 Instructor: Michael Eckmann.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
Improving structure with inheritance 3.0. The media project stores details about CDs and DVDs –CD: title, artist, number of tracks, playing time, got-it,
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
28-Dec-04polymorhism.ppt1 Polymorphism. 28-Dec-04polymorhism.ppt2 signatures in any programming language, a signature is what distinguishes one function.
Coming up Which methods are where? – Overriding Calling super’s methods Coupling and cohesion.
Comp1004: Conclusions Revision Session. Coming up Recap – The Basics – The Pillars – The Extras Feedback + Course Evaluation Structure of the Exam Some.
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Coming up Inheritance – Code duplication – Super classes – Constructors Polymorphic collections – “Anywhere a super class is, a sub class can go” Casting.
EKT472: Object Oriented Programming Overloading and Overriding Method.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Overriding Method.
Chapter 9 Inheritance and Polymorphism
Inheritance, Polymorphism, and Interfaces. Oh My
More about inheritance
Polymorphism 28-Nov-18.
Chapter 11 Inheritance and Polymorphism
Java Inheritance.
Polymorphism 15-Apr-19.
Comp1202: Inheritance I Super and Sub-classes.
Polymorphism 21-Apr-19.
Chapter 11 Inheritance and Polymorphism Part 1
Improving structure with inheritance
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

Comp1004: Inheritance II Polymorphism

Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism – Designing for Polymorphism – The super keyword

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Inheritance Reminder The sub-classes inherit all the properties and methods from the superclass Any class that is inherited from is called a superclass Any class that inherits from another is called a subclass They can also add more of their own

Inheritance in Java public class Item { private String title; private int playingTime; private boolean gotIt; private String comment; // constructors and methods omitted. } You don’t need to add anything to the superclass

Inheritance in Java You don’t need to add anything to the superclass public class CD extends Item { private String artist; private int numberOfTracks; // constructors and methods omitted. } public class DVD extends Item { private String director; // constructors and methods omitted. } You declare the inheritance in the sub-class using the extends keyword

Encapsulation Expanded In fact Java uses several keywords for encapsulation Public – Everyone can see it Protected – Only this class, its sub-classes and the package can see it Default (no keyword) – Only this class and the package can see it Private – Only this class can see it

Encapsulation Expanded Rule-of-thumb: assume everything should be protected In fact Java uses several keywords for encapsulation Public – Everyone can see it Protected – Only this class, its sub-classes and the package can see it Default (no keyword) – Only this class and the package can see it Private – Only this class can see it

Encapsulation Expanded Rule-of-thumb: assume everything should be protected Explicitly make public the methods (and sometimes properties) that you want other classes to use Explicitly make private any implementation details that you want to hide even from sub-classes In fact Java uses several keywords for encapsulation Public – Everyone can see it Protected – Only this class, its sub-classes and the package can see it Default (no keyword) – Only this class and the package can see it Private – Only this class can see it

Encapsulation Expanded Rule-of-thumb: assume everything should be protected Explicitly make public the methods (and sometimes properties) that you want other classes to use Explicitly make private any implementation details that you want to hide even from sub-classes You will probably end up with few protected things at all! In fact Java uses several keywords for encapsulation Public – Everyone can see it Protected – Only this class, its sub-classes and the package can see it Default (no keyword) – Only this class and the package can see it Private – Only this class can see it

Overriding Methods

The Animal Class public class Animal { // constructors omitted public void sleep() { System.out.println(“zzz”); } public void roam() { System.out.println(“wanders about”); } public void eat() { System.out.println(“eats something”); } A simple Animal class. Here the three methods just print out what happens when an animal sleeps, roams or eats

An Animal Class Hierarchy Animal sleep roam eat sleep roam eat

Dog Is a type of Animal Dogs sleep like any other animal But eats meat and roams in packs They have their own way of doing those things So we give them their own methods which are more specific than the animal class

The Dog Class public class Dog extends Animal { // constructors omitted public void roam() { System.out.println(“roams in packs”); } public void eat() { System.out.println(“eats meat”); } The Dog inherits the sleep method from Animal But defines its own versions of roam and eat We say that it overrides the roam and eat method from Animal This means it replaces them with more specific methods for itself

An Animal Class Hierarchy Animal sleep roam eat sleep roam eat Dog roam eat roam eat

The Cat Class public class Cat extends Animal { // constructors omitted public void roam() { System.out.println(“roams independently”); } public void eat() { System.out.println(“eats meat”); } The Cat inherits the sleep method from Animal But defines its own versions of roam and eat We say that it overrides the roam and eat method from Animal This means it replaces them with more specific methods for itself

An Animal Class Hierarchy Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat

The Elephant Class public class Elephant extends Animal { // constructors omitted public void eat() { System.out.println(“eats grass”); } The Elephant inherits the sleep and roam methods from Animal But defines its own versions of eat We say that it overrides the eat method from Animal This means it replaces it with a more specific method for itself

An Animal Class Hierarchy Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat

Overriding Replacing a super-class’ method with one in its sub-class is called overriding This is not the same as overloading – Overloading is writing two or more methods in the same class with the same name but different signatures (return types and parameter lists) When overriding the signatures must be the same

Which method gets called? Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat Animal a = new Animal(); a.sleep();

Which method gets called? Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat Animal a = new Animal(); a.sleep();

Which method gets called? Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat Animal a = new Animal(); a.sleep(); Dog d = new Dog(); d.sleep(); d.eat();

Which method gets called? Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat Animal a = new Animal(); a.sleep(); Dog d = new Dog(); d.sleep(); d.eat();

Overriding The first method found from the bottom of the inheritance tree is called This means you can override methods from almost all the classes – Although the keyword final will stop you overriding methods. We will study it later.

Dynamic Binding

Which method gets called? Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat Animal a = new Animal(); a.sleep(); Dog d = new Dog(); d.sleep(); d.eat(); Animal c = new Cat(); c.eat();

Which method gets called? Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat Animal a = new Animal(); a.sleep(); Dog d = new Dog(); d.sleep(); d.eat(); Animal c = new Cat(); c.eat();

Which method gets called? Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat Animal a = new Animal(); a.sleep(); Dog d = new Dog(); d.sleep(); d.eat(); Animal c = new Cat(); c.eat(); Animal d2 = d; d2.roam();

Which method gets called? Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat Animal a = new Animal(); a.sleep(); Dog d = new Dog(); d.sleep(); d.eat(); Animal c = new Cat(); c.eat(); Animal d2 = d; d2.roam();

Dynamic Binding Java is calling the most specific version of the method, even when the reference has the type of the superclass This is called dynamic binding, because Java doesn’t figure out which version of the method to call until runtime

Dynamic Binding is Very Useful ArrayList animals; animals = new ArrayList (); animals.add(new Animal()); animals.add(new Dog()); animals.add(new Cat()); animals.add(new Elephant()); Remember that we can use a subclass whenever a reference or collection is expecting the superclass – this is called substitution

Dynamic Binding is Very Useful ArrayList animals; animals = new ArrayList (); animals.add(new Animal()); animals.add(new Dog()); animals.add(new Cat()); animals.add(new Elephant()); for(Animal a : animals) { a.sleep(); a.eat(); a.roam(); } Remember that we can use a subclass whenever a reference or collection is expecting the superclass – this is called substitution Because of dynamic binding these will call the most specific version of the method, even though we iterating through an Animal collection

Dynamic Binding is Very Useful ArrayList animals; animals = new ArrayList (); animals.add(new Animal()); animals.add(new Dog()); animals.add(new Cat()); animals.add(new Elephant()); for(Animal a : animals) { a.sleep(); a.eat(); a.roam(); } Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat

Dynamic Binding is Very Useful ArrayList animals; animals = new ArrayList (); animals.add(new Animal()); animals.add(new Dog()); animals.add(new Cat()); animals.add(new Elephant()); for(Animal a : animals) { a.sleep(); a.eat(); a.roam(); } Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat

Dynamic Binding is Very Useful ArrayList animals; animals = new ArrayList (); animals.add(new Animal()); animals.add(new Dog()); animals.add(new Cat()); animals.add(new Elephant()); for(Animal a : animals) { a.sleep(); a.eat(); a.roam(); } Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat

Dynamic Binding is Very Useful ArrayList animals; animals = new ArrayList (); animals.add(new Animal()); animals.add(new Dog()); animals.add(new Cat()); animals.add(new Elephant()); for(Animal a : animals) { a.sleep(); a.eat(); a.roam(); } Animal sleep roam eat sleep roam eat Dog roam eat roam eat Cat roam eat roam eat Elephant eat

Polymorphism

Substitution, Overriding and Dynamic Binding gives us Polymorphism – (greek for many shapes) Polymorphism means that we can create methods that deal with superclasses and then: – We can pass them instances of sub-classes (substitution) – And when it calls methods on those sub-classes if there are more specific methods defined (via overriding) the call gets diverted at run-time to the most specific method (dynamic binding)

Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Example: Object.toString() Methods in Object are inherited by all classes. – Any of these may be overridden. The toString method is commonly overridden: – public String toString() – Returns a string representation of the object. Calls to println automatically result in toString being called in the appropriate sub-class: – System.out.println(item);

Designing for Polymorphism “We have a system that needs to send messages to people. Usually we contact people via , but some like to be contacted via SMS and some via snail mail. What sort of class structure might we build?”

Designing for Polymorphism “We have a system that needs to send messages to people. Usually we contact people via , but some like to be contacted via SMS and some via snail mail. What sort of class structure might we build?” Broker sendMsg SMSBroker number sendMsg SnailBroker address sendMsg

Designing for Polymorphism ArrayList brokers; Brokers = new ArrayList (); brokers.add(new brokers.add(new brokers.add(new SMSBroker(“ ”)); brokers.add(new SnailBroker(“1600 Penns Ave. D.C.”)); brokers.add(new SMSBroker(“ ”)); String message = “Reminder. Fix economy!”); for(Broker b : brokers) { b.sendMsg(message); } Broker sendMsg SMSBroker number sendMsg SnailBroker address sendMsg

The Three Pillars of OOP EncapsulationInheritancePolymorphism

The super keyword public class Broker{ //code omitted public void sendMsg(String msg) { //code to send omitted } public class SMSBroker extends Broker{ //code omitted public void sendMsg(String msg) { //code to send SMS omitted } What happens if we want to access a method in the superclass – i.e. perhaps as well as sending an SMS the SMSBroker also wants an ? Broker sendMsg SMSBroker number sendMsg SnailBroker address sendMsg

The super keyword public class Broker{ //code omitted public void sendMsg(String msg) { //code to send omitted } public class SMSBroker extends Broker{ //code omitted public void sendMsg(String msg) { super.sendMsg(msg); //code to send SMS omitted } What happens if we want to access a method in the superclass – i.e. perhaps as well as sending an SMS the SMSBroker also wants an ? Broker sendMsg SMSBroker number sendMsg SnailBroker address sendMsg Within a sub-class we can use super to access protected or public methods in the superclass

Summary Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism – Designing for Polymorphism – The super keyword