CMSC 202 Class Reuse with Inheritance. 2 Acknowledgement The code examples in this presentatio are adapted from “Thinking in Java”, 4ed, by Bruce Eckel.

Slides:



Advertisements
Similar presentations
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 4 : Polymorphism King Fahd University of Petroleum & Minerals College of Computer.
Advertisements

CMSC 202 Inheritance. Aug 6, Object Relationships An object can have another object as one of instance variables. The Person class had two Date.
Comp 249 Programming Methodology Chapter 7 - Inheritance – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Chapter 7 Inheritance Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
CS102--Object Oriented Programming Lecture 7: – Inheritance Copyright © 2008 Xiaoyan Li.
© 2006 Pearson Addison-Wesley. All rights reserved8-1 The final Modifier A method marked final indicates that it cannot be overridden with a new definition.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
CS102--Object Oriented Programming Lecture 8: – More about Inheritance When to use inheritance Relationship between classes Rules to follow Copyright ©
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.
Chapter 7 Inheritance Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
Computer Science I Inheritance Professor Evan Korth New York University.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Comp 249 Programming Methodology Chapter 8 - Polymorphism Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
CMSC 202 Inheritance II. Version 10/102 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
CMSC 202 Inheritance I Class Reuse with Inheritance.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
CMSC 202 Inheritance II. Version 10/092 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
Creating Classes from Other Classes Appendix D © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
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.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
CMSC 202 Polymorphism. 10/20102 Topics Binding (early and late) Upcasting and downcasting Extensibility The final modifier with  methods  classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
CMSC 202 Polymorphism 2 nd Lecture. Aug 6, Topics Constructors and polymorphism The clone method Abstract methods Abstract classes.
Inheritance and Polymorphism
Polymorphism 2nd Lecture
Polymorphism 2nd Lecture
Road Map Inheritance Class hierarchy Overriding methods Constructors
Comp 249 Programming Methodology
Inheritance 2nd Lecture
Chapter 7 Inheritance Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Polymorphism 2nd Lecture
Comp 249 Programming Methodology
Inheritance I Class Reuse with Inheritance
Comp 249 Programming Methodology
Inheritance 2nd Lecture
CMSC 202 Inheritance.
Class Reuse with Inheritance
Inheritance 2nd Lecture
CMSC 202 Inheritance II.
Chapter 7 Inheritance.
Presentation transcript:

CMSC 202 Class Reuse with Inheritance

2 Acknowledgement The code examples in this presentatio are adapted from “Thinking in Java”, 4ed, by Bruce Eckel and are covered by the copyright notice on the last slide in this presentation.

3 Class Reuse with Composition We have seen how classes (and their code) can be reused with composition.  An object has another object as one (or more) of its instance variables. Composition models the “has a” relationship.  A Person has a String (name)  A Car has an Engine  A Book has an array of Pages

4 Object Relationships An object can be a specialized version of another object.  A Car is a Vehicle  A Triangle is a Shape  A Doctor is a Person  A Student is a Person This kind of relationship is known as the “is a type of” relationship. In OOP, this relationship is modeled with the programming technique known as inheritance. Inheritance creates new classes by adding code to an existing class. The existing class is reused without modification

5 Introduction to Inheritance Inheritance is one of the main techniques of OOP. Using inheritance  a very general class is first defined,  then more specialized versions of the class are defined by adding instance variables and adding methods.  The specialized classes are said to inherit the methods and instance variables of the general class. Copyright © 2008 Pearson Addison-Wesley. All rights reserved

6 A simple example ( 1 of 3) In this example, we first define a general Cleanser class. class Cleanser { private String label = "Cleanser"; public void append(String s) { label += s; } public void dilute() { append(" dilute()"); } public void apply() { append(" apply()"); } public void scrub() { append(" scrub()"); } public String toString() { return label; } public static void main(String[] args) { Cleanser x = new Cleanser(); x.dilute(); x.apply(); x.scrub(); System.out.println(x); } // Output Cleanser dilute() apply() scrub()

7 A simple example ( 2 of 3) We now define Detergent as a type of Cleanser. public class Detergent extends Cleanser { // add an instance variable private String size = “Large”; // Change a method public void scrub(){ append(size + " Detergent.scrub()"); } // Add method(s) to the interface: public void foam(){ append(" foam()"); } // Test the new class: public static void main(String[] args) { Detergent x = new Detergent(); x.dilute(); x.apply(); x.scrub(); x.foam(); System.out.println(x); } // Output Cleanser dilute() apply() Large Detergent.scrub() foam()

8 A simple example ( 3 of 3) We now define Bleach as another type of Cleanser. public class Bleach extends Cleanser { // Add method(s) to the interface: public void whiten(){ append(" Bleach whiten()"); } // Test the new class: public static void main(String[] args) { Detergent x = new Detergent(); x.dilute(); x.apply(); x.scrub(); x.whiten(); System.out.println(x); } // Output Cleanser dilute() apply() scrub() Bleach whiten()

9 A closer look Keyword extends to define Detergent and Bleach  implements inheritance Detergent, Bleach are derived from Cleanser  Cleanser is the base class  Detergent, Bleach are the derived classes Detergent’s and Blach’s interfaces automatically includes all of Cleanser’s interface  We say “Detergent inherits Cleanser’s public methods” Detergent add its own method, foam(), to the interface Detergent changes the implementation of scrub(), but not its interface Detergent adds its own instance variable (size) to support foam() Bleach adds its own method, whiten() to the interface

10 Inheritance and OOP Inheritance is an abstraction for  sharing similarities among classes label, dilute( ), apply( ), toString( )  preserving their differences Detergent’s scrub(), foam() Bleach’s whiten( ). Inheritance allows us to group classes into families of related types (Cleanser), allowing for the sharing of common operations and data.

11 A Class Hierarchy Copyright © 2008 Pearson Addison-Wesley. All rights reserved Cleanser append() apply() dilute() scrub() toString() Detergent foam() scrub() Bleach whiten()

12 Derived Classes Since Detergent “is a type of” Cleanser, it is defined as a derived class (or subclass )of the Cleanser class. (ditto for Bleach)  A derived class is defined by using the keyword extends adding instance variables and/or methods redefining a method  The class that the derived class is built upon is called the base class or superclass.  A derived class inherits the instance variables and methods of the base class that it extends. Copyright © 2008 Pearson Addison-Wesley. All rights reserved

13 Derived Class Interface The derived class’ interface automatically has of the base class public methods Implementations of the inherited base class public methods do not appear in the derived class.  The code is reused without having to explicitly copy it

14 Overriding a Method Definition A derived class can change the implementation of a base class public method  scrub() in Detergent  Known as method overriding  The signature of the method is NOT changed Name Parameters (order and types) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

15 Overriding Versus Overloading Do not confuse overriding a method in a derived class with overloading a method name.  When a method in a derived class has the same signature as the method in the base class, that is overriding.  When a method in a derived class or the same class has a different signature from the method in the base class or the same class, that is overloading.  Note that when the derived class overrides or overloads the original method, it still inherits the original method from the base class as well. Copyright © 2008 Pearson Addison-Wesley. All rights reserved

16 Reusing a Base Class method The Detergent class redefined the scrub() method from Cleanser public class Detergent extends Cleanser { // add an instance variable private String size = “Large”; // Change a method public void scrub(){ append(size + " Detergent.scrub()"); } But suppose this method wanted to call scrub() defined in Cleanser. If scrub() simply calls scrub(), we would produce a recursive call. To solve this problem we need a generic name for the base class. In Java, the gereric base class name is super. // Change a method public void scrub(){ append(size + " Detergent.scrub()"); super.scrub( ); // the base class implementation }

17 Derived Object Creation To the derive class user, there appears to be just one object, but… An object of a derived class is really two objects  The derived class object itself  The base class subobject It’s important to guarantee that both parts of the derived object are initialized correctly during object construction The base class constructor must be called as part of the derived class object construction mechanism

18 Construction and Inheritance // Constructor calls during inheritance. public class Art { Art() { System.out.println("Art constructor"); } } public class Drawing extends Art { Drawing() { System.out.println("Drawing constructor"); } } public class Cartoon extends Drawing { public Cartoon() { System.out.println("Cartoon constructor"); } public static void main(String[] args) { Cartoon x = new Cartoon(); } // Output: Art constructor Drawing constructor Cartoon constructor

19 A Closer Look Construction starts at the base class and works down the hierarchy Java automatically inserts a call to the base class default constructor which is called before the code in the derived class is executed. Only a base class constructor can initialize private instance variables in the base class To pass arguments to an alternative base class constructor, explicitly call the alternative base class constructor using super()

20 Constructors with Arguments public class Game { private int gameNr Game(int i) { System.out.println("Game constructor” + i); gameNr = i; } public class BoardGame extends Game { BoardGame(int i) { super(i);// call Game(i) System.out.println("BoardGame constructor”) } public class Chess extends BoardGame { Chess() { super(11);// call BoardGame(11) System.out.println("Chess constructor"); } public static void main(String[] args) { Chess x = new Chess(); } // Output: Game constructor 11 BoardGame constructor Chess constructor

21 The Big Idea Inheritance implements the “is a type of” relationship between two classes -- the derived class is a type of the base class. The derived class is a “specialized” form of the more general base class Conceptually this means  An Object of a derived class has more than one type  An object of a derived class has the type of the derived class, and it also has the type of the base class  More generally, an object of a derived class has the type of every one of its ancestor classes In practice this means  An object of a derived class can be plugged in as a parameter in place of any of its ancestor classes  In fact, a derived class object can be used anyplace that an object of any of its ancestor types can be used

22 “Is-a-type-of” Example The “is a type of’ relationship is supported by OOP languages public class Instrument { public void play() { /* some code here */ } static void tune(Instrument i) { //... i.play(); } // Wind objects are instruments // because they have the same interface: public class Wind extends Instrument { public static void main(String[] args) { Wind flute = new Wind(); // passing a Wind to tune() Instrument.tune(flute); } }

23 Upcasting Inheritance guarantees that all methods defined in the base class will be available in the derived class.  Since Instrument has play( ) so will Wind  The code in tune( ) will work for an Instrument or a Wind The act of converting a Wind reference to an Instrument reference (when tune() is called) is referred to as upcasting.  Casting from the derived class to the base class move “up” the inheritance hierarchy.

24 “is-a”type-of” in a Nutshell Assume that class D (Derived) is derived from class B (Base). 1. Every object of type D is a type of B, but not vice versa. 2. D is a more specialized version of B. 3. Anywhere an object of type B can be used, an object of type D can be used just as well, but not vice versa. (Adapted from: Effective C++, 2nd edition, pg. 155)

25 The Class Object In Java, every class is a descendent of the class Object  Every class has Object as its ancestor  Every object of every class is of type Object, as well as being of the type of its own class If a class is defined that is not explicitly a derived class of another class, it is still automatically a derived class of the class Object Copyright © 2008 Pearson Addison-Wesley. All rights reserved

26 The Class Object The class Object is in the package java.lang which is always imported automatically Having an Object class enables methods to be written with a parameter of type Object  A parameter of type Object can be replaced by an object of any class whatsoever  For example, some library methods accept an argument of type Object so they can be used with an argument that is an object of any class Copyright © 2008 Pearson Addison-Wesley. All rights reserved

27 The Class Object The class Object has some methods that every Java class inherits  For example, the equals and toString methods Every object inherits these methods from some ancestor class  Either the class Object itself, or a class that itself inherited these methods (ultimately) from the class Object However, these inherited methods should be overridden with definitions more appropriate to a given class  Some Java library classes assume that every class has its own version of such methods Copyright © 2008 Pearson Addison-Wesley. All rights reserved

28 The Right Way to Define equals Since the equals method is always inherited from the class Object, methods like the following simply overload it: public boolean equals(Cleanser otherCleanser) {... } However, this method should be overridden, not just overloaded: public boolean equals(Object otherObject) {... } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

29 The Right Way to Define equals The overridden version of equals must meet the following conditions  The parameter otherObject of type Object must be type cast to the given class (e.g., Cleanser)  However, the new method should only do this if otherObject really is an object of that class, and if otherObject is not equal to null  Finally, it should compare each of the instance variables of both objects Copyright © 2008 Pearson Addison-Wesley. All rights reserved

30 A Better equals Method for the Class Cleanser public boolean equals(Object otherObject) { if(otherObject == null) return false; else if(getClass( ) != otherObject.getClass( )) return false; else { // Downcast Object to Cleanser Cleanser otherCleanser = (Cleanser) otherObject; // compare instance variable(s) using their equals() method return label.equals(otherCleanser.label; } Copyright © 2008 Pearson Addison-Wesley. All rights reserved

31 The getClass() Method Every object inherits the same getClass() method from the Object class An invocation of getClass() on an object returns a representation only of the class that was used with new to create the object  The results of any two such invocations can be compared with == or != to determine whether or not they represent the exact same class (object1.getClass() == object2.getClass()) Copyright © 2008 Pearson Addison-Wesley. All rights reserved

32 Pitfall: Use of Private Base Class Instance Variables An instance variable that is private in a base class is not accessible by name in a method definition of a derived class.  An object of the Detergent class cannot access the private instance variable label by name, even though it is inherited from the Employee base class. Instead, a private instance variable of the base class can only be accessed by the accessor and mutator methods defined in base class. If private instance variables of a class were accessible in method definitions of a derived class, …  then anytime a class implementer wanted to access a private instance variable of a class, they would only need to create a derived class, and access the variables in a method of that class.  this would allow private instance variables to be changed by mistake or in inappropriate ways. Copyright © 2008 Pearson Addison-Wesley. All rights reserved

33 Pitfall: Private Methods Are Effectively Not Inherited The private methods of the base class are like private variables in terms of not being directly available. A private method is completely unavailable, unless invoked indirectly.  This is possible only if an object of a derived class invokes a public method of the base class that happens to invoke the private method. This should not be a problem because private methods should be used only as helper methods.  If a method is not just a helper method, then it should be public. Copyright © 2008 Pearson Addison-Wesley. All rights reserved

34 Protected Access If a method or instance variable is modified by protected (rather than public or private ), then it can be accessed by name  Inside its own class definition  Inside any class derived from it The protected modifier provides very weak protection compared to the private modifier  It allows direct access to any programmer who defines a suitable derived class  Therefore, instance variables should normally not be marked protected To make instance variables accessible to derived classes, yet still inaccessible from the class user  Define the instance variables as private  Provide protected accessors/mutators Copyright © 2008 Pearson Addison-Wesley. All rights reserved

35 Inheriting Static Variables Static variables in a base class are inherited by any of its derived classes The modifiers public, private, and protected have the same meaning for static variables as they do for instance variables Copyright © 2008 Pearson Addison-Wesley. All rights reserved

36 Inheritance and the final modifier final methods  May not be overridden so the implementation may not be changed in a derived class  May be more efficient since the compiler may choose to insert the body of the method in place of the method call  private methods are implicitly final final classes  May not be extended  Male their methods implicitly final Copyright © 2008 Pearson Addison-Wesley. All rights reserved

37 Composition vs. Inheritance Composition  “has a” relationship  Functionality of an existing class Don’t expose its interface to client programmer Defined as private instance variable Inheritance  “is a type of” relationship  Specialize a general class Extend interface Modify implementation of method(s)

38 Combining Composition and Inheritance Much OOP code is created by combining existing class. This example creates a somewhat complex class using both composition and inheritance public class Plate { Plate(int i) { System.out.println("Plate constructor"); } public class DinnerPlate extends Plate { DinnerPlate(int i) { super(i); System.out.println("DinnerPlate constructor"); }

39 Example (cont’d) public class Utensil { Utensil(int i) { System.out.println("Utensil constructor"); } public class Spoon extends Utensil { Spoon(int i) { super(i); System.out.println("Spoon constructor"); } public class Fork extends Utensil { Fork(int i) { super(i); System.out.println("Fork constructor"); }

40 Example (cont’d) public class Knife extends Utensil { Knife(int i) { super(i); System.out.println("Knife constructor"); } // A cultural way of doing something: public class Custom { Custom(int i) { System.out.println("Custom constructor"); }

41 Example (cont’d) public class PlaceSetting extends Custom { private Spoon sp; private Fork frk; private Knife kn; private DinnerPlate pl; public PlaceSetting(int i) { super(i + 1); sp = new Spoon(i + 2); frk = new Fork(i + 3); kn = new Knife(i + 4); pl = new DinnerPlate(i + 5); System.out.println("PlaceSetting constructor"); } public static void main(String[] args) { PlaceSetting x = new PlaceSetting(9); }

42 Output from Example Code Custom constructor Utensil constructor Spoon constructor Utensil constructor Fork constructor Utensil constructor Knife constructor Plate constructor DinnerPlate constructor PlaceSetting constructor

43 “Thinking in Java” Copyright This computer source code is Copyright (c)2006 MindView, Inc. All Rights Reserved. Permission to use, copy, modify, and distribute this computer source code (Source Code) and its documentation without fee and without a written agreement for the purposes set forth below is hereby granted, provided that the above copyright notice, this paragraph and the following five numbered paragraphs appear in all copies. 1. Permission is granted to compile the Source Code and to include the compiled code, in executable format only, in personal and commercial software programs. 2. Permission is granted to use the Source Code without modification in classroom situations, including in presentation materials, provided that the book "Thinking in Java" is cited as the origin. 3. Permission to incorporate the Source Code into printed media may be obtained by contacting: MindView, Inc Valle Vista La Mesa, California The Source Code and documentation are copyrighted by MindView, Inc. The Source code is provided without express or implied warranty of any kind, including any implied warranty of merchantability, fitness for a particular purpose or non- infringement. MindView, Inc. does not warrant that the operation of any program that includes the Source Code will be uninterrupted or error-free. MindView,Inc. makes no representation about the suitability of the Source Code or of any software that includes the Source Code for any purpose. The entire risk as to the quality and performance of any program that includes the Source Code is with the user of the Source Code. The user understands that the Source Code was developed for research and instructional purposes and is advised not to rely exclusively for any reason on the Source Code or any program that includes the Source Code. Should the Source Code or any resulting software prove defective, the user assumes the cost of all necessary servicing, repair, or correction. 5. IN NO EVENT SHALL MINDVIEW, INC., OR ITS PUBLISHER BE LIABLE TO ANY PARTY UNDER ANY LEGAL THEORY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS, OR FOR PERSONAL INJURIES, ARISING OUT OF THE USE OF THIS SOURCE CODE AND ITS DOCUMENTATION, OR ARISING OUT OF THE INABILITY TO USE ANY RESULTING PROGRAM, EVEN IF MINDVIEW, INC., OR ITS PUBLISHER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. MINDVIEW, INC. SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOURCE CODE AND DOCUMENTATION PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, WITHOUT ANY ACCOMPANYING SERVICES FROM MINDVIEW, INC., AND MINDVIEW, INC. HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.