F II 8. More on Inheritance Objectives

Slides:



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

INHERITANCE BASICS Reusability is achieved by INHERITANCE
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
1 OOP in C#:Object Interaction. Inheritance and Polymorphism. Session 2: OOP in C#
Chapter 8 Improving Structure with Inheritance. The DoME Example The Database of Multimedia Entertainment We will be storing information about CDs and.
1 Inheritance Concepts n Derive a new class (subclass) from an existing class (base class or superclass). n Inheritance creates a hierarchy of related.
Improving structure with inheritance (Chapters 8 and 9)
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.
Object-Orientated Design and Programming Unit 8: Inheritance and Polymorphism Jin Sa.
CPSC150 Abstract Classes Chapter 10. CPSC150 Directory Example (note: your assignment does not have all of this) DirectoryEntry name phone public void.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
More about inheritance Exploring polymorphism 5.0.
Abstract Classes and Interfaces
More about inheritance Exploring polymorphism 3.0.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
1 Inheritance and Polymorphism Andrew Davison Noppadon Kamolvilassatian Department of Computer Engineering Prince of Songkla University.
CC1007NI: Further Programming Week 2 Dhruba Sen Module Leader (Islington College)
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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Viswanathan Inheritance and Polymorphism Course Lecture Slides 2 nd June 2010 “ We are.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
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.
Session 2: OOP in C# OOP in C#: –Object Interaction. –Inheritance and Polymorphism. Autumn 20121UCN Technology: IT/Computer Science.
More about inheritance Exploring polymorphism 5.0.
CSE 1341 Honors Professor Mark Fontenot Southern Methodist University Note Set 17.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Objects First With Java A Practical Introduction Using BlueJ Method overriding 2.0.
Session 06: C# OOP-3 Inheritance and Polymorphism. Static and dynamic type of an object. FEN AK - IT: Softwarekonstruktion.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
EKT472: Object Oriented Programming Overloading and Overriding Method.
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Overriding Method.
Chapter 11 Inheritance and Polymorphism
Inheritance and Polymorphism
More about inheritance
More about inheritance
Chapter 5 Hierarchies IS-A associations superclasses subclasses
COS 260 DAY 19 Tony Gauvin.
Interfaces and Inheritance
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Object Oriented Programming
CSC 143 Inheritance.
Chapter 9 Inheritance and Polymorphism
CSC 113 Tutorial QUIZ I.
Inheritance Basics Programming with Inheritance
Lecture 19 - Inheritance (Contd).
Extending Classes.
More about inheritance
Polymorphism and access control
Inheritance and Polymorphism
CS18000: Problem Solving and Object-Oriented Programming
Computer Programming with JAVA
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Comp1202: Inheritance I Super and Sub-classes.
Chapter 11 Inheritance and Polymorphism Part 1
CIS 110: Introduction to computer programming
Presentation transcript:

242-210 F II 8. More on Inheritance Objectives the use of super, overriding, method polymorphism (dynamic binding), protected access, toString() Original Slides by Dr. Andrew Davison

Topics 1. Students Example 2. Method Polymorphism 3. Extends and Private 4. DoME v.2 Output Problem 5. The Object Class's Methods

1. Students Example Develop a class called Student Use it to define a subclass called GradStudent

Student.java continued public class Student { private int student_id; private int year; private String name; public Student(String nm, int id, int y) { name = new String(nm); student_id = id; year = y; } continued

public String toString() { return "Student: " + name + ", " + public String toString() { return "Student: " + name + ", " + student_id + ", " + year; } public int year_group() { return year; } } // end of Student class

GradStudent.java continued public class GradStudent extends Student { private String dept; private String thesis; // constructor public GradStudent(String nm, int id, int y, String d, String th) { super(nm, id, y); // call superclass constructor dept = new String(d); thesis = new String(th); } continued

public String toString() { return "Grad " + super. toString() + ", " + public String toString() { return "Grad " + super.toString() + ", " + dept + ", " + thesis; } } // end of GradStudent class

TestStuds.java continued public class TestStuds { public static void main(String args[]) { Student s1 = new Student("Jane Doe", 100, 1); GradStudent gs1; gs1 = new GradStudent("John Smith", 200, 4, "Pharmacy", "Retail Thesis"); : continued

System. out. println("Student s1"); System. out. println(s1 System.out.println("Student s1"); System.out.println(s1.toString()); System.out.println("Year " + s1.year_group() + "\n"); System.out.println("GradStudent gs1"); System.out.println(gs1.toString()); System.out.println("Year " + gs1.year_group() + "\n"); : // see later } } // end of TestStuds class

Compilation and Execution $ javac Student.java $ javac GradStudent.java $ javac TestStuds.java $ java TestStuds

TestStuds Output $ java TestStuds Student s1 Student: Jane Doe, 100, 1 Year 1 Grad student gs1 GradStudent: John Smith, 200, 4, Pharmacy, Retail Thesis Year 4 : // see later

Objects Diagrams Student s1 GradStudent gs1 student_id 100 student_id 200 year 1 year 4 name “Jane Doe” name “John Smith” Student object dept “Pharmacy” thesis “Retail Thesis” GradStudent object

Method Lookup for s1.toString() Student s1 Student object instance of

Method Lookup for gs1.toString() GradStudent gs1 GradStudent object instance of Overriding: use the first version of toString() found in the inheritance hierarchy.

Super Calls in Methods Overridden methods are hidden ... ... but we still want to be able to call them. An overridden method can be called from the method that overrides it with: super.method(...) compare with the use of super in constructors

Method Lookup for gs1.year_group() GradStudent gs1 GradStudent object instance of Move up the inheritance hierarchy until a suitable method is found.

TestStuds.java Continued : Student stud; stud = gs1; // refer to subclass System.out.println("Student stud"); System.out.println( stud.toString() ); System.out.println("Year " + stud.year_group()); } } // end of TestStuds class

Objects Diagram student_id 200 GradStudent gs1 year 4 Student stud name “John Smith” dept “Pharmacy” gs1 and stud refer to the same object thesis “Retail Thesis” GradStudent object

Output Student stud Grad Student: John Smith, 200, 4, Pharmacy, Retail Thesis Year 4 Even though stud is of type Student, it can refer to a GradStudent object because GradStudent is a subclass of Student

Method Lookup of stud.toString() Student stud GradStudent object instance of Overriding again: use the first version found.

2. Method Polymorphism A superclass variable can store subclass objects. Method calls are polymorphic: the chosen method depends on the object often called dynamic binding since the choice of method is made at run-time

Method Polymorphism Example Student stud; GradStudent g; PostGradStudent p; : stud = new Student(); stud.toString(); // which toString()? val = // some input number if (val == 1) stud = g; else stud = p; stud.toString(); // which toString()?

The toString() method used by stud will vary over time initially it will be the one in Student later, depending on the value of val, it will be the method in GradStudent or PostGradStudent the JVM can only choose the right class when the code is executed (i.e. at run-time)

3. Extends and Private Student has three private variables (student_id, name, year) which are inherited by GradStudent what does this mean? Private variables in a superclass cannot be directly seen or changed by a subclass. continued

A better object diagram: This means that methods in the GradStudent class cannot directly see or change student_id, name, or year how can they be seen/changed? A better object diagram: student_id 200 year 4 name “John Smith” GradStudent gs1 dept “Pharmacy” thesis “Retail Thesis” continued

The creator of a class with private variables can also include public get/set methods for them: public class Student { private String name: : public String getName() { return name; } public void setName(String n) { name = n; } : } A bad design choice. continued

Usage in GradStudent.java: public String changeName(...) { String name = getName(); // change name in some way setName( name ): } In the user’s code: GradStudent gs = new GradStudent(…); gs.setName(“andy”); probably a bad idea to allow this continued

The better solution is to use protected. Public get/set methods allow subclasses to see/change private variables, but they also can be used by users this solution destroys the interface that's why it's a bad design choice The better solution is to use protected.

Protected Variables Better, but still not the best design choice. The protected variables of a superclass can be accessed by methods in subclasses (and by other classes in the package) but they are private to users of the class this level of visibility is between public and private

Example public class Student { private int student_id; private int year; protected String name; : } Now GradStudent can use name directly, but cannot see/change student_id or year: name = "andrew"; // in GradStudent Users of Student cannot see/change any of the variables.

Protected Methods The best design choice. The best approach is to use protected get/set methods for a private variable: public class Student { private String name; // stays private : protected String getName() { return name; } protected void setName(String n) { name = n; } : }

Protected methods hide the implementation of name from GradStudent the interface is maintained Protected methods cannot be called by the users of Student or GradStudent.

Summary of the Approaches How do we make inherited private data accessible to subclass methods? Three approaches: public methods exposes inherited class to user; bad protected variables variables only visible to subclass, but subclass sees implementation; not good protected methods best

4. DoME v.2 Output Problem Some information isn't printed What we get CD: A Swingin' Affair (64 mins)* Frank Sinatra tracks: 16 my favourite Sinatra album   DVD: O Brother, Where Art Thou? (106 mins) Joel & Ethan Coen The Coen brothers’ best movie! What we get in DoME v.1 title: A Swingin' Affair (64 mins)* my favourite Sinatra album title: O Brother, Where Art Thou? (106 mins) The Coen brothers’ best movie! What we get in DoME v.2 Some information isn't printed

The Inheritance Hierarchy uses At runtime, a call to print() will use Item.print(). is a

The Reason for the Problem The print() method in Item only prints the fields defined in Item. Inheritance only works 'upwards': a subclass inherits its superclass fields and methods The superclass method (e.g. print()) knows nothing about its subclass’s fields or methods.

The Solution: Overriding print() in super- and subclasses. uses CD and DVD print() will use super.print() to print the Item info is a At runtime, a call to print() will use either CD.print() or DVD.print() .

CD's print() // in the CD class public void print() { System.out.println("CD: " + artist); System.out.println("tracks: " + numTracks); super.print(); // print info stored in Item }

5. The Object Class’s Methods Methods in Object are inherited by all classes. any of these may be overridden The toString() method is often overridden public String toString() returns a string representation of the object

Overriding toString() public class Item { : public String toString() String info = title + " (" + playingTime + " mins)"); if(gotIt) return info + "*\n" + " " + comment + "\n"); else return info + "\n" + " " + comment + "\n"); } // end of toString() } // end of Item class

Using toString() Instead of a print() method use toString(): System.out.println( item.toString() ); println() will call an object's toString() method automatically, so the above call can be simplified to: System.out.println( item );