More about inheritance Exploring polymorphism 5.0.

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

A subclass can add new private instance variables A subclass can add new public, private or static methods A subclass can override inherited methods A.
Inheritance. Class Relationships Composition: A class contains objects of other class(es) (actually, references to such objects) –A “has a” relationship.
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)
Improving structure with inheritance
More about inheritance Exploring polymorphism. 02/12/2004Lecture 8: More about inheritance2 Main concepts to be covered method polymorphism static and.
Understanding class definitions Looking inside classes 3.0.
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.
Understanding class definitions – Part II –. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
More about inheritance Exploring polymorphism 5.0.
More about inheritance Exploring polymorphism 3.0.
CC1007NI: Further Programming Week 2 Dhruba Sen Module Leader (Islington College)
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
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.
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables Objects First with Java.
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables Objects First with Java.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Topic 4 Inheritance.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Understanding class definitions
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
Objects First With Java A Practical Introduction Using BlueJ Method overriding 2.0.
1 COS 260 DAY 19 Tony Gauvin. 2 Agenda Questions? 8 th Mini Quiz not corrected yet 9 Th Mini Quiz next class –Due November 19 Finish Discussion on More.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Session 06: C# OOP-3 Inheritance and Polymorphism. Static and dynamic type of an object. FEN AK - IT: Softwarekonstruktion.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
1 COS 260 DAY 17 Tony Gauvin. 2 Agenda Questions? 7 th Mini quiz –Chapter 7 –Password “GoBengals” –40 min Assignment 4 posted –Due Nov 9 (one week) Capstone.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
1 COS 260 DAY 18 Tony Gauvin. 2 Agenda Questions? 7 th Mini quiz Graded –Good results 8 th Mini Quiz –Chap 8  Next class Assignment 4 Due Assignment.
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
1 Topic 5 Polymorphism "“Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.”
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables © 2017 Pearson Education,
9 Improving structure with inheritance
Lecture 12 Inheritance.
Chapter 11 Inheritance and Polymorphism
More about inheritance
10 More about inheritance
More about inheritance
COS 260 DAY 19 Tony Gauvin.
Continuing Chapter 11 Inheritance and Polymorphism
Overloading and Constructors
COS 260 DAY 19 Tony Gauvin.
Lecture 19 - Inheritance (Contd).
Extending Classes.
Java Programming Language
More about inheritance
COS 260 DAY 18 Tony Gauvin.
Topic 5 Polymorphism "“Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.”
Understanding class definitions
COS 260 DAY 4 Tony Gauvin.
F II 8. More on Inheritance Objectives
Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String toString()
Presentation transcript:

More about inheritance Exploring polymorphism 5.0

2 Main concepts to be covered method polymorphism static and dynamic type overriding dynamic method lookup protected access Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

3 The inheritance hierarchy Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling display() method is in superclass Post

4 Conflicting output Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Leonardo da Vinci Had a great idea this morning. But now I forgot what it was. Something to do with flying seconds ago - 2 people like this. No comments. Alexander Graham Bell [experiment.jpg] I think I might call this thing 'telephone'. 12 minutes ago - 4 people like this. No comments. Leonardo da Vinci 40 seconds ago - 2 people like this. No comments. Alexander Graham Bell 12 minutes ago - 4 people like this. No comments. What we want (original w/o inheritance) What we have (results w/ inheritance)

5 The problem The display method in Post only prints the common fields Inheritance is a one-way street: –A subclass inherits the superclass fields –Superclass knows nothing about subclass’s fields Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

6 Attempting to solve the problem Place display where it has access to the information it needs Each subclass has its own version But Post ’s fields are private NewsFeed cannot find a display method in Post Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

7 Static type and dynamic type A more complex type hierarchy requires further concepts to describe it Some new terminology: –static type –dynamic type –method dispatch/lookup Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

8 Static and dynamic type Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Car c1 = new Car(); What is the type of c1? Vehicle v1 = new Car(); What is the type of v1?

9 Static and dynamic type Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Car c1 = new Car(); What is the type of c1? Vehicle v1 = new Car(); What is the type of v1? Car (type) Vehicle (static type) Car (dynamic type)

10 Static and dynamic type The declared type of a variable is its static type The type of the object a variable refers to is its dynamic type The compiler’s job is to check for static-type violations: for(Post post : posts) { post.display(); // Compile-time error. } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

11 Overriding: the solution Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling display method in both super- and subclasses Satisfies both static and dynamic type checking NOTE: display method in Post would never execute!

12 Overriding Superclass and subclass define methods with the same signature Each has access to the fields of its own class Superclass satisfies static type check Subclass method is called at runtime – it overrides the superclass version What becomes of the superclass version? Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

13 Distinct static and dynamic types Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling The variable post has a: static type of Post dynamic type of PhotoPost

14 Method lookup Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling No inheritance or polymorphism. The obvious method is selected. display is executed from PhotoPost

15 Method lookup Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Inheritance (without overriding) where the inheritance hierarchy is ascended, searching for a match. display is NOT found in PhotoPost, but it is found and executed from Post

16 Method lookup Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Polymorphism and overriding exists, where search starts with dynamic type (ascending up) and the first version found is used. display is found & executed in PhotoPost

17 Method lookup summary The variable is accessed The object stored in the variable is found The (dynamic) class of the object is found The class is searched for a method match If no match is found, the superclass is searched This is repeated until a match is found, or the class hierarchy is exhausted Overriding methods take precedence Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

18 Super call in methods Overridden methods are hidden, but we may still want to be able to call them An overridden method can be called from the method that overrides it by using super ( i.e. super.method() ) Compare with the use of super in constructors ( i.e. super() ) –method name is explicitly stated ( i.e. super.method () ) –s uper.method may be used anywhere, and not just the first statement (as with constructors) –no automatic super call (as in constructors) is generated, nor is a super.method call required

19 Calling an overridden method Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public void display() { super.display(); System.out.println(" [" + filename + "]"); System.out.println(" " + caption); } Calls the superclass display method and then continues with printing its own fields.

20 Method polymorphism We have been discussing polymorphic method dispatch A polymorphic variable can store objects of varying types Method calls are also polymorphic –The actual method called depends on the dynamic object type Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

21 The Object class’s methods Methods in the Object library class are inherited by ALL classes Any of those found in Object may be overridden ( i.e. toString ) The implicitly-defined toString method is commonly overridden: –public String toString() –r eturns a string representation of the object Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

22 Overriding toString in Post Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public String toString() { String text = username + "\n" + timeString(timestamp); if(likes > 0) { text += " - " + likes + " people like this.\n"; } else { text += "\n"; } if(comments.isEmpty()) { return text + " No comments.\n"; } else { return text + " " + comments.size() + " comment(s). Click here to view.\n"; }

23 Overriding toString Explicit print methods can often be omitted from a class: System.out.println(post.toString()); Calls to println and print with just an object automatically result in toString being called: System.out.println(post); Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

24 StringBuilder Consider using StringBuilder as an alternative to concatenation: StringBuilder builder = new StringBuilder(); builder.append(username); builder.append('\n'); builder.append(timeString(timestamp)); … return builder.toString(); Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling The overloaded append method takes a parameter of any type and effectively converts it to its string representation before appending it to the original StringBuilder object.

25 Object equality What does it mean for two objects to be ‘the same’? –Reference equality (only 1 object) –Content equality (2 objects with the same internal states) Compare use of == with equals() in with strings in the String class: –== compares reference equality –equals() compares content equality

26 Overriding equals public boolean equals(Object obj) { if(this == obj) { return true; // reference to itself } if(!(obj instanceof ThisType)) { return false; // different object types } ThisType other = (ThisType) obj; // cast into right variable type return field.equals(other.field) && … // compare all field contents of this and other } // for content equality public boolean equals(Object obj) { return this == obj; // reference to itself } Object class method actually tests for reference equality! To test for content equality, we must override the method!

27 Overriding equals in Student public boolean equals(Object obj) { if(this == obj) { return true; // reference equality } if(!(obj instanceof Student)) { return false; // different object types } Student other = (Student) obj; // cast return name.equals(other.name) && id.equals(other.id) && credits == other.credits; } // test content equality

28 Overriding hashCode in Student /** * Uses values of name, id & credits fields * to calculate the distinct hashCode * representation of a specific Student object */ public int hashCode() { int result = 17; result = 37 * result + name.hashCode(); result = 37 * result + id.hashCode(); result = 37 * result + credits; return result; } hashCode method should also be overridden whenever the equals method is overridden.

29 Protected access Private access in the superclass may be too restrictive for a subclass The closer inheritance relationship is supported by protected access Protected access is more restricted than public access But allows access to fields/methods within a class itself AND from all its subclasses –protected accessors, mutators & constructors We still recommend keeping fields private –to maintain encapsulation

30 Access levels Method calls from Subclass to protected methods in its superclass SomeClass are made similar to calls to its own internal methods. Thus, NO object variable (with dot notation) is necessary. getSomeClassField()

31 The instanceof operator Used to determine the dynamic type Recovers ‘lost’ type information Usually precedes assignment with a cast to the dynamic type: if(post instanceof MessagePost) { MessagePost msg =(MessagePost) post; … access MessagePost methods via msg … } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

32 Review The declared type of a variable is its static type –Compilers check static types The type of an object is its dynamic type –Dynamic types are used at runtime Methods may be overridden in a subclass Method lookup starts with the dynamic type Protected access supports inheritance Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling