Computer Science and Engineering College of Engineering The Ohio State University Lot More Inheritance and Intro to Design Patterns Lecture 12.

Slides:



Advertisements
Similar presentations
1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
Advertisements

1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
ITEC200 – Week03 Inheritance and Class Hierarchies.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Inheritance One of the biggest advantages of object-oriented design is that of inheritance. A class may be derived from another class, the base class.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
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.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
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.
Java Implementation: Part 3 Software Construction Lecture 8.
Computer Science and Engineering College of Engineering The Ohio State University Interfaces The credit for these slides goes to Professor Paul Sivilotti.
What is inheritance? It is the ability to create a new class from an existing class.
Non-static classes Part 2 1. Methods  like constructors, all non-static methods have an implicit parameter named this  for methods, this refers to the.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
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.
Object Oriented Programming
Lecture 4: Extending Classes. Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
1 Chapter 4 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Subclassing, pt. 2 Method overriding, virtual methods, abstract classes/methods COMP 401, Fall 2014 Lecture 9 9/16/2014.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance ndex.html ndex.htmland “Java.
Inheritance and Polymorphism
1 Chapter 2 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
BY:- TOPS Technologies
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Lecture 12 Inheritance.
Chapter 11 Inheritance and Polymorphism
Inheritance and Polymorphism
Chapter 3 Inheritance © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Chapter 9 Inheritance and Polymorphism
Extending Classes.
Week 6 Object-Oriented Programming (2): Polymorphism
Chapter 9 Inheritance and Polymorphism
Chapter 8 Class Inheritance and Interfaces
CIS 110: Introduction to computer programming
Presentation transcript:

Computer Science and Engineering College of Engineering The Ohio State University Lot More Inheritance and Intro to Design Patterns Lecture 12

Computer Science and Engineering The Ohio State University Recall: Interface Inheritance void select (Person p) { //declared type of p is: //dynamic type of p is: person student Every student is a person Person Student SmartPerson OsuStudent implements extends

Computer Science and Engineering The Ohio State University Recall: Behavioral Subtyping  A Student can do everything a Person can do  Everywhere a Person is expected, a Student can be used instead void select (Person p) { if (p.getAge() > 18) { p.summons(Date trialDate);... etc...  Every method promised in Person interface: Is implemented in SmartPerson class Is promised in Student interface Is implemented in OsuStudent class  Are two separate implementations of getAge really necessary (or even a good idea)?

Computer Science and Engineering The Ohio State University Generics and Inheritance  Is a Stack a Stack ? Can a Stack do everything a Stack can do? Can code expecting a Stack be given a Stack instead?  Java’s choice: No! For a generic class G, there is no implicit subtyping relationship between G and G Neither covariance nor contravariance Regardless of any subtyping relationship between A and B

Computer Science and Engineering The Ohio State University Implementation Inheritance  Keyword: extends public class OsuStudent extends SmartPerson {... } OsuStudent has SmartPerson’s members (fields + methods, including implementation) If omitted, java.lang.Object is implicit Person Student SmartPerson OsuStudent implements extends

Computer Science and Engineering The Ohio State University Class Hierarchy  Inheritance is transitive  Every class inherits from java.lang.Object CseMajorCseGrad OsuStudent SmartPerson Object OsuFaculty extends DnaCreature Parent Child Base Derived Super Sub

Computer Science and Engineering The Ohio State University java.lang.Object  The root of all class hierarchies This is a class called “Object” There is also a class in java.lang called “Class”!  Provides several useful methods getClass()  Returns Class of the object instance String toString()  Returns String representing object value boolean equals(Object)  Returns true iff argument is equal to object int hashCode()  Returns an int “hash value” for object Object clone()  Creates and returns a copy (here be dragons…)

Computer Science and Engineering The Ohio State University The getClass() Method  Returns an instance of java.lang.Class Generic class: Class String getName()  Name of the class as a string, eg “CseMajor”  Think of it as representing the object’s class Student s1 = new OsuStudent(); Student s2 = new CseMajor(); System.out.println(s1.getClass().getName()); System.out.println(s2.getClass().getName()); if (s1.getClass() == s2.getClass()) {...  Of course (?) java.lang.Class extends Object! Try not to think about this too hard

Computer Science and Engineering The Ohio State University Good Practice: Core Methods  Always override toString() Default implementation gives class name + a meaningless hex number  eg  Always override equals() Default implementation checks object references for equality Pencil p1 = new LeadedPencil(); Pencil p2 = new LeadedPencil(); assert(!p1.equals(p2));  Always override hashCode() Default implementation is memory address What is a hashCode? Stay tuned...  clone(): To override or not? Things get very dicey here

Computer Science and Engineering The Ohio State University Class and Interface Hierarchies CseMajorCseGrad OsuStudent SmartPerson Object OsuFaculty Voter Salaried implements extends Voter v = new SmartPerson(); v = new OsuStudent(); v = new CseGrad(); v = new OsuFaculty();

Computer Science and Engineering The Ohio State University Mechanics  A class extends exactly one other class “single inheritance” (cf C++)  A subclass has all the members of its superclass! Not the private members Not the constructors (ie just fields and methods)  Subclass can add new members (hence “extends”) New fields and new methods Defines its own constructor(s)  Subclass can modify inherited methods Changes behavior “overriding”

Computer Science and Engineering The Ohio State University Example: Code class SmartPerson { private String name; SmartPerson () { this.name = “Baby Doe”; } SmartPerson (String name) { this.name = name; } void rename (String name) { this.name = name; } String getName () { return this.name; } class OsuStudent extends SmartPerson { private int ID; OsuStudent () { this.ID = 0; } OsuStudent (String name, int ID) { super(name); this.ID = ID; } boolean winsTicketLottery () { return (this.ID % 2 == 0); } String toString () { return this.getName() + “ [“ + this.ID + “]”; }

Computer Science and Engineering The Ohio State University Example: Graphical View winsTicket…() ID toString() OsuStudent() rename()getName() SmartPerson() name rename()getName() SmartPerson() name SmartPerson p = new SmartPerson() OsuStudent s = new OsuStudent()

Computer Science and Engineering The Ohio State University Constructing New Instances  Members of OsuStudent: its own: ID, winsTicketLottery(), toString() its parent’s: rename(), getName() its parent’s parent’s: see java.lang.Object  eg clone(), equals(), hashCode(),…  When a new instance is created: First, the parent’s constructor is invoked  Can be done explicitly with super()  Otherwise, parent’s default constructor is called Next, any initialization blocks are executed Finally, the child’s constructor is executed

Computer Science and Engineering The Ohio State University Overriding Methods  Overriding: a subclass declares a method that is already present in its superclass  Note: signatures must match (otherwise it is just overloading) class SmartPerson { String toString() { return this.getName(); } class OsuStudent extends SmartPerson { String toString() { return this.getName() + “ [“ + this.ID + “]”; }  Question: which method is called? SmartPerson p = new OsuStudent(); System.out.println(p.toString()); Declared type: SmartPerson, dynamic type: OsuStudent

Computer Science and Engineering The Ohio State University Polymorphism  Answer: The dynamic type determines which method is called SmartPerson p = new OsuSudent(); p.toString() //calls OsuStudent version  Informal model: Method invocation is a run-time message to the object That (run-time) object receives the request, performs the action, and returns the result  Goal: we get the right behavior regardless of actual (ie run-time, ie dynamic) type Person[] csePeople = … //students & faculty in CSE for (int i = 0; i < csePeople[].length; i++) { csePeople[i].toString(); }  Note: this applies to methods only, not fields Fields can not be overridden, only hidden

Computer Science and Engineering The Ohio State University Good  annotation with all methods intended to override a method in a superclass class OsuStudent extends SmartPerson String getName() {... }  Compiler complains if there is no matching method in superclass Prevents accidental overloading if a mistake is made in the signature  Beware: Differences between Java 5 & 6

Computer Science and Engineering The Ohio State University Hook methods  Dynamic type of this controls which method executes  Hook method: Called internally, intended to be overridden class Course { void enroll(Student s) { if (checkEligibility(s)) { … } } boolean checkEligibility(Student s) { //determines whether s has prereqs for this course } class Tutorial extends Course { boolean checkEligibility(Student s) { //determines whether s has paid }  Yo-yo problem: Must trace up & down class hierarchy to understand code Course workshop = new Tutorial(); workshop.enroll(s);

Computer Science and Engineering The Ohio State University Hook and Template Pattern  Recall pattern: Base class contains both template and hook methods Template method calls this.hook method Hook methods are overridden in derived classes Template method is not  To support this pattern: Template method is declared final Hook methods are declared abstract  So base class declared abstract too Hook methods are declared protected  See divide-and-conquer example solve() is the template method

Computer Science and Engineering The Ohio State University Hook and Template, and Abstract Classes public abstract class Course { public final void enroll(Student s) { if (checkEligibility(s)) { … } } protected abstract boolean checkEligibility(Student s); } public class Tutorial extends Course protected boolean checkEligibility(Student s) { //determines whether s has paid }

Computer Science and Engineering The Ohio State University Protected  We have seen three levels of visibility private: concrete representation default (ie package): trusted and co-located public: abstract interface to all clients  Writing a subclass often requires: More access than a generic client Less access than whole concrete representation  Solution: new visibility level Keyword: protected Protected members are inherited but are not part of the public interface to generic clients Warning: anyone can extend your class and then has access to protected members

Computer Science and Engineering The Ohio State University Good Practice: Limited Use  Getting it right is hard  Unless you have an explicit need for an open (ie extendable) class hierarchy, prevent others from extending your classes  Keyword final prevents extensions public final class Faculty {... } public class Administrator extends Faculty {... //compiler complains }  If you do have a specific need to allow extensions, design for it carefully Use protected diligently and carefully (it’s a huge increase in visibility over private or even over package!) Chances are, it will still be broken

Computer Science and Engineering The Ohio State University Summary  Implementation (class) inheritance Declaration syntax: extends just like interfaces Vocabulary: super/sub, base/derived, parent/child  Class and interface hierarchies Constructing new instances  Overriding and polymorphism Signature must match exactly Dynamic type controls implementation Hook methods: dynamic type of this  Protected visibility  Limiting extension: final

Computer Science and Engineering The Ohio State University Supplemental Reading  Bloch’s “Effective Java”, chapter 3 See Safari Books Online link Warning: favors instanceOf over getClass  Better for behavioral subtyping  Worse for creating an equivalence relation  IBM developerWorks paper “Java Theory and practice: Hashing it out” /library/j-jtp05273.html  Various blogs (all slightly broken) ch/java/equalhash.html