Class Design III: Advanced Inheritance Additional References “Object-Oriented Software Development Using Java”, Xiaoping Jia, Addison Wesley, 2002 “Core.

Slides:



Advertisements
Similar presentations
5/17/2015 OO Design: Liskov Substitution Principle 1.
Advertisements

Inheritance Inheritance Reserved word protected Reserved word super
Inheritance and object compatibility Object type compatibility An instance of a subclass can be used instead of an instance of the superclass, but not.
ITEC200 – Week03 Inheritance and Class Hierarchies.
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,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Inheritance. 2 Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class or superclass.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Inheritance (notes for 10/26 lecture). Inheritance Inheritance is the last of the relationships we will study this semester. Inheritance is (syntactically)
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Criteria for good design. aim to appreciate the proper and improper uses of inheritance and appreciate the concepts of coupling and cohesion.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Criteria for good design. aim to appreciate the proper and improper uses of inheritance and appreciate the concepts of coupling and cohesion.
Chapter 10 Classes Continued
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
© 2006 Pearson Addison-Wesley. All rights reserved9 A-1 Chapter 9 Advanced Java Topics CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2007.
Computer Science I Inheritance Professor Evan Korth New York University.
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
Subclasses and Subtypes CMPS Subclasses and Subtypes A class is a subclass if it has been built using inheritance. ▫ It says nothing about the meaning.
Intro to OOP with Java, C. Thomas Wu
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
Outline §Review of the last class l class variables and methods l method overloading and overriding §Inheritance and polymorphism l polymorphism l abstract.
Object-Oriented Design CSC 212. Announcements This course is speeding up and we are starting new material. Please see me if you feel this is going too.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
OO as a language for acm l OO phrase l Mental model of key concepts.
Programming in Java CSCI-2220 Object Oriented Programming.
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.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Subtype Polymorphism, Subtyping vs
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
Evaluating an Object-Oriented Design ©SoftMoore ConsultingSlide 1.
1. Perspectives on Design Principles – Semantic Invariants and Design Entropy Catalin Tudor 2.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
CSCI-383 Object-Oriented Programming & Design Lecture 24.
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
FEN 2014UCN Teknologi/act2learn1 Object-Oriented Programming “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle.
CSCI 383 Object-Oriented Programming & Design Lecture 22 Martin van Bommel.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
Advanced Programming in Java
Week 4 Object-Oriented Programming (1): Inheritance
Road Map Inheritance Class hierarchy Overriding methods Constructors
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Overloading and Constructors
Extending Classes.
Java Programming Language
MSIS 670 Object-Oriented Software Engineering
Advanced Java Topics Chapter 9
Week 6 Object-Oriented Programming (2): Polymorphism
Subtype Polymorphism, Subtyping vs
Chapter 9 Carrano Chapter 10 Small Java
Presentation transcript:

Class Design III: Advanced Inheritance Additional References “Object-Oriented Software Development Using Java”, Xiaoping Jia, Addison Wesley, 2002 “Core Java 2”, Cay Hortsmann, Gary Cornell, Sun Microsystems Press, 2003 You should be able to: describe the open-closed principle, why it matters, and how it applies to object-oriented code. use overloading correctly and recognize inappropriate uses describe the Liskov Substitution Principle (LSP) explain whether or not a given design adheres to the LSP incorporate inheritance into the design of software systems so that the LSP is respected compare and contrast the use of inheritance and delegation use delegation and interfaces to realize multiple inheritance in design (e.g., to support the implementation of multiple types) identify elements of a given design that violate the basic design principles of low coupling and high cohesion

Background: class member visibility public: Other classes can access these classes, fields, or methods private: Only the declaring class can access these classes, fields, or methods protected: The declaring class and all sub-classes can access these classes fields, or methods package protected: Other classes in the same package can access these classes, fields or methods This is the default visibility, when no keyword is used

Class Design III: Good/Bad Practices 3 To Overload or Not to Overload Overloading: Same name is used for more than one method in the same class Mainly used for convenience Misuse may reduce program readability Should use overloading only in two situations: There is a general description that fits all overloaded methods All overloaded methods have the same functionality (some may provide default arguments)

Class Design III: Good/Bad Practices 4 To Overload or Not to Overload Overloading: Same name is used for more than one method in the same class Mainly used for convenience Misuse may reduce program readability Should use overloading only in two situations: There is a general description that fits all overloaded methods All overloaded methods have the same functionality (some may provide default arguments)

Class Design III: Good/Bad Practices 5 Overloading Examples Good: Bad: class StringBuffer { StringBuffer append(char c) { … } StringBuffer append(int i) { … } StringBuffer append(float f) { … } … class Employee { //sets employee’s name void name(String s) { … } // returns employee’s name String name() { … } … Do both fit under a common description?

Class Design III: Good/Bad Practices 6 Method Dispatch: Find the right method declaration for a given method call. METHOD CALL object.methodCallName(arg1, arg2,.., argN) METHOD DECLARATION returnType declaredMethodName(parm1, parm2,.., parmN) {.. } Overall strategy: 1. Find candidate method signatures (FindSignature) 2. Use the most specific candidate signature found (FindMostSpecific) 3. Find a method matching that signature in the most specific class (FindMethod)

Class Design III: Good/Bad Practices 7 Method Dispatch: Which method signatures are candidates? FindSignature 1. In the reference type (i.e. static type) of the target object, select the set of method signatures where... Declared name matches called method name Number of declared parameters matches number of actual arguments passed to method call 2. From this set, restrict the set to those where... The reference type (i.e. static type) of each passed argument, matches or is a subtype of the corresponding parameter in a declared method signature

Class Design III: Good/Bad Practices 8 Method Dispatch: Which exact method signature will the target method have? FindMostSpecific 1. From the candidates, select the one signature whose declared parameter types are furthest from Object in the inheritance hierarchy These types are said to be the most specific 2. In the case that some types are more specific for some parameters in a signature, but less specific for some parameters Compile time error, i.e. Java will not allow this

Class Design III: Good/Bad Practices 9 Method Dispatch: Which method with that signature is executed? FindMethod 1. Take the signature identified in FindMostSpecific Don’t worry about which class it came from or which method implementation was associated with the signature 2. Now, select the class for the actual (runtime) type of the object the method is being called on (i.e. the target object). 3. If that class has a method exactly matching the right method signature, execute that method, else repeat for super-class, etc.. etc..

Class Design III: Good/Bad Practices 10 Overloading Example public class Employee { public void name(String s) { … } public void name(Object o) { … } } In Main: String stringAsString = new String(“aString”); Object stringAsObject = stringAsString; Employee e = new Employee(); e.name(stringAsObject); // what gets called? e.name(stringAsString); // what gets called?

Class Design III: Good/Bad Practices 11 Open-Closed Principle Classes should be open for extension but closed for modification Want to extend the behaviour of our system by adding subclasses without having to modify the superclasses The principle suggests you should consider possible future subclasses when defining a class

Class Design III: Good/Bad Practices 12 is-a Style Inheritance : The right way In addition to the required Java inheritance declaration (extends), subclasses must logically be a subtype of supertype based on class contract Liskov Substitution Principle or LSP A subclass can weaken the preconditions “A subclass can require less restrictions” “A subclass can accept a larger range of values” A subclass can strengthen the postconditions “A subclass can provide more guarantees” “A subclass can return a smaller range of values”

Class Design III: Good/Bad Practices 13 is-a Style Inheritance: The right way… Program should be able to use cars without having to know exactly which kind of car it is: void navigateToDestination(Car c) { c.turnLeft();... } Car … turnLeft( ): void turnRight( ): void … HybridCarHummer

Class Design III: Good/Bad Practices 14 Weakening the precondition A subclass method can weaken the precondition (but it cannot strengthen it) when overriding a method from its superclass. The subclass can accept a wider range of values as input. class Payment { /** amt >= 0 */ void setPaymentAmount(int amt) {…} } class CreditCardPayment extends Payment { /** true */ void setPaymentAmount(int amt) {…} } class CashPayment extends Payment { … }

Class Design III: Good/Bad Practices 15 Weakening the precondition Why does it not make sense to strengthen the precondition? Suppose we set the precondition on the setPaymentAmount of CreditCardPayment to amt >= 25 Client should be able to do: Payment p; // substitute CashPayment for Payment p = new CashPayment(); p.setPaymentAmount( 5 );... // substitute CreditCardPayment for Payment p = new CreditCardPayment(); p.setPaymentAmount( 5 ); // oops!

Class Design III: Good/Bad Practices 16 Strengthening the postcondition A subclass’s method can strengthen the postcondition (but it cannot weaken it): a subclass‘s method can return a subset of the values returned by the method it overrides. class Payment { /** returns >= 0 */ double getInterest() {…} } class CreditCardPayment extends Payment { /** return 4.25 */ double getInterest() {…} } class CashPayment extends Payment { … } }

Class Design III: Good/Bad Practices 17 Strengthening the postcondition Why does it not make sense to weaken the postcondition? Suppose the client writes code based on the postcondition of the superclass. That client code could break if we substitute a superclass object with an instance of one of its subclasses if the subclass' method has a weaker postcondition. Example: client writes code assuming that a method returns a value that is positive subclass overrides method to return *any* value (so postcondition is weakened) client code is going to break if a negative value is returned.

Class Design III: Good/Bad Practices 18 Limitation Inheritance : The wrong way Subclass restricts rather than extends the behavior inherited from the superclass Violates is-a relationship Violates the Liskov Substitution Principle Usually used for implementation convenience (obviously in the wrong way) Example Square defined as a subclass of Rectangle (next slide) Methods setHeight and setWidth are not applicable to a square

Class Design III: Good/Bad Practices 19 Example: Rectangle Class class Rectangle { private double height; // class invariant height>0 private double width; // class invariant width>0 Rectangle(double h, double w) { height = h; width = w; } void setHeight(double h) { height = h; } void setWidth(double w){ width = w; }

Class Design III: Good/Bad Practices double area() { return height * width; } Example: Rectangle Class (continued)

Class Design III: Good/Bad Practices 21 Example : Square Class (the wrong way) class Square extends Rectangle { Square() { super(); } Square( double s) { super(s, s); }... What is wrong with this?

Class Design III: Good/Bad Practices // Override setHeight and setWidth void setHeight(double l) { ?????? } void setWidth(double l) { ??????? } void setSide(double s){ super.setHeight(s); super.setWidth(s); } Example : Square Class (the wrong way, cont...)

Class Design III: Good/Bad Practices 23 Example: Rectangle Class (revised) class NewRectangle { protected double height; // class invariant height>0 protected double width; // class invariant width>0 Rectangle(double h, double w) { height = h; width = w; } double getArea() { return height*width; }

Class Design III: Good/Bad Practices 24 Example: Square Class (a correct way) class NewSquare extends NewRectangle { NewSquare(double s) { super(s, s); } void setSides(double s){ height = s; width = s; }

Class Design III: Good/Bad Practices 25 Delegation – another form of re-use A method delegates the execution of a task to another object of a different type Think of the “other object” as a servant used to carry out the task In OO languages delegation can be: - class-based (or static)‏ servant is a component of the class –method-based (or dynamic)‏ method creates a servant and delegates the service Example next slide: –Square defined using class based delegation

Class Design III: Good/Bad Practices 26 Square Class (a right way)‏ public class Square { private Rectangle rectangle; public Square() { rectangle = new Rectangle(); } public Square(double s) { rectangle = new Rectangle(s, s); }

Class Design III: Good/Bad Practices 27 public void setSide(double s){ rectangle.growToWidth(s); } public double area() { return rectangle.area(); } Square Class (a right way)‏

Class Design III: Good/Bad Practices 28 Multiple Inheritance Multiple inheritance occurs when a class has more than one super-class. Multiple inheritance is supported by some programming languages (e.g., C++) but not others (e.g., Java). Multiple inheritance can lead to problems, for example, the classic diamond problem: StudentEmployee TeachingAssistant Person Suppose Person has a method myMethod() that's overridden in a different way in Student and Employee and that's not overridden in TeachingAssistant. Which version of the method should the following code call: TeachingAssistant ta = new TeachingAssistant(); ta.myMethod();

Class Design III: Good/Bad Practices 29 Handling Multiple Inheritance in Java We can use delegation to implement multiple class inheritance if necessary For instance: instead of this: you can do this: StudentEmployee TeachingAssistant StudentInterfaceEmployeeInterface Employee Student

Class Design III: Good/Bad Practices 30 Multiple Inheritance Example interface StudentInterface { public float getGPA(); } interface EmployeeInterface { public float getSalary(); } public class Student implements StudentInterface { protected float GPA; public float getGPA() { // code for GPA }

Class Design III: Good/Bad Practices 31 public class Employee implements EmployeeInterface { protected float salary; public float getSalary() { // code for Salary } public class TeachingAssistant implements StudentInterface, EmployeeInterface { private Student student; private Employee employee; Multiple Inheritance Example (continued)

Class Design III: Good/Bad Practices 32 Multiple Inheritance Example (continued) public TeachingAssistant() { student = new Student(); employee = new Employee(); } public float getGPA() { return student.getGPA(); } public float getSalary() { return employee.getSalary(); }

Class Design III: Good/Bad Practices 33 Name Collisions Among Interfaces A Java class may extend another class and implement one or more interfaces Inherited method from one interface may have same name as a method in another class or interface Name Collision procedure: if methods have different signatures, they are considered overloaded if they have same signature and return type, they are one method if they have same signature, different return types, produce compilation error if they have same signature and return type, but throw different exceptions, they are one method that throws the union of the exceptions thrown by each of them

Class Design III: Good/Bad Practices 34 General Design Guidelines for Inheritance Place common attributes and methods in the superclasses Use inheritance to model only is-a type relationships Use abstract classes and interfaces to design extensible families of objects with common properties e.g., employees of different types e.g., different types of objects to be drawn in a CAD application

Class Design III: Good/Bad Practices 35 Exercise Which is the right way to define ellipse and circle? Ellipse + setMajorAxis(double):void + setMinorAxis(double):void Circle + setRadius(double):void Ellipse + setMajorAxis(double):void + setMinorAxis(double):void Circle + setRadius(double):void

Class Design III: Good/Bad Practices 36 Key Concepts In This Lecture There are a lot of related concepts we covered in this lecture When you design a superclass, think about whether it might be extended in the future (i.e., which methods should be protected instead of private, etc.). This is the open-closed principle in action. In Java, a subclass is considered a subtype as is an implementation of an interface. To ensure an instance of a subclass (or a class that extends an interface) is substitutable for its superclass (or its interface) we need to follow the Liskov Substitutability Principle (LSP). i.e., watch out that pre-conditions and post-conditions of overridden methods do the right thing. If we want to reuse code but can’t do it via a subclass because we’d violate the LSP, we can use delegation where we keep an object of the type from which we want the code and we call the object’s methods to do the work we want done. If we want one class to include behavior from different types, use interfaces (and sometimes delegation too!)