© 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341.

Slides:



Advertisements
Similar presentations
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Advertisements

1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Intro to CS – Honors I Inheritance and Polymorphism GEORGIOS PORTOKALIDIS
CSE 1302 Lecture 8 Inheritance Richard Gesick Figures from Deitel, “Visual C#”, Pearson.
CMSC 202 Inheritance. Aug 6, Object Relationships An object can have another object as one of instance variables. The Person class had two Date.
 2005 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Object-Oriented Programming: Inheritance Deitel &Deitel Java SE 8.
ITEC200 – Week03 Inheritance and Class Hierarchies.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Creating Classes from Other Classes Chapter 2 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CSCI 143 OOP – Inheritance 1. What is Inheritance? A form of software reuse Create a new class from an existing class – Absorb existing class data and.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
©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 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 10 Classes Continued
© 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not be copied or used for any.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
 2005 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Inheritance.
 2005 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Inheritance.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
Chapter 8 More Object Concepts
CISC6795: Spring Object-Oriented Programming: Polymorphism.
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.
What is inheritance? It is the ability to create a new class from an existing class.
More on Object-Oriented Programming: Inheritance 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Peyman Dodangeh Sharif University of Technology Fall 2014.
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Unit 2 Review (Part 1) Arrays, Inheritance, and the Ethical Use of Computers.
© 2007 Lawrenceville Press Slide 1 Chapter 8 Objects  A variable of a data type that is a class. Also called an instance of a class.  Stores data  Can.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
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.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
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.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Object-Oriented Programming: Polymorphism Chapter 10.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Inheritance and Polymorphism
Object-Oriented Programming: Inheritance
Week 4 Object-Oriented Programming (1): Inheritance
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Chapter 9 Object-Oriented Programming: Inheritance
Extending Classes.
Lecture 22 Inheritance Richard Gesick.
Inheritance, Polymorphism, and Interfaces. Oh My
Advanced Programming Behnam Hatami Fall 2017.
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Java Inheritance.
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Chapter 11 Inheritance and Polymorphism Part 1
Presentation transcript:

© 2013 Ken Howard, Southern Methodist University Object-Oriented Programming: Inheritance CSE 1341

© 2013 Ken Howard, Southern Methodist University Abstraction

© 2013 Ken Howard, Southern Methodist University Abstraction

© 2013 Ken Howard, Southern Methodist University Building Church Residence Office School Cathedral

© 2013 Ken Howard, Southern Methodist University Die A die component: Has a face value. Can roll itself — “Do It Myself.” RegularDie -faceValue: int +RegularDie() +getFaceValue(): int +setFaceValue(int):void +roll():int +RegularDie() +getFaceValue(): int +setFaceValue(int):void +roll():int

© 2013 Ken Howard, Southern Methodist University Die A die component: Has a face value. Can roll itself — “Do It Myself.” RegularDie -faceValue: int +Die() +getFaceValue(): int +setFaceValue(int):void +roll():int +Die() +getFaceValue(): int +setFaceValue(int):void +roll():int

© 2013 Ken Howard, Southern Methodist University Extending the Die Class Objects (software components) can have variations on a theme. Consider a new kind of Die, LoadedDie, that can remember a loaded side and set the value of half of the rolls to the loadedSide. LoadedDie -faceValue: int -loadedSide: int -faceValue: int -loadedSide: int +LoadedDie() +getFaceValue(): int +setFaceValue(int):void +getLoadedSide() : int +setLoadedSide(int):void +roll():int +LoadedDie() +getFaceValue(): int +setFaceValue(int):void +getLoadedSide() : int +setLoadedSide(int):void +roll():int

© 2013 Ken Howard, Southern Methodist University Die and LoadedDie: Common Parts LoadedDie -faceValue: int -loadedSide: int +LoadedDie() +getFaceValue(): int +setFaceValue(int):void +getLoadedSide() : int +setLoadedSide(int):void +roll():int RegularDie -faceValue: int +RegularDie() +getFaceValue(): int +setFaceValue(int):void +roll():int +RegularDie() +getFaceValue(): int +setFaceValue(int):void +roll():int

© 2013 Ken Howard, Southern Methodist University Inheritance LoadedDie -loadedSide: int +LoadedDie() +getLoadedSide() : int +setLoadedSide(int):void +roll() : int RegularDie -faceValue: int +RegularDie() +getFaceValue(): int +setFaceValue(int):void +roll():int +RegularDie() +getFaceValue(): int +setFaceValue(int):void +roll():int over-ridden inherited added inherited Superclass Subclass

© 2013 Ken Howard, Southern Methodist University Inheritance LoadedDie -loadedSide: int +LoadedDie() +getLoadedSide() : int +setLoadedSide(int):void +roll() : int RegularDie -faceValue: int +Die() +getFaceValue(): int +setFaceValue(int):void +roll():int +Die() +getFaceValue(): int +setFaceValue(int):void +roll():int Inheritance: – Is present when software classes are organized in a generalization- specialization hierarchy. – Means that a subclass acquires all of the attribute and method definitions of its superclass. A subclass can add its own unique attributes and behaviors. A subclass might also override (redefine) an inherited method. Advantages? over-ridden inherited added inherited

© 2013 Ken Howard, Southern Methodist University Polymorphism Polymorphism means: – The same message can be interpreted in different ways, depending on the receiver. – A method by the same name can be defined in different classes. How do you know which method will be executed when you send a message? Advantages? roll() RegularDie LoadedDie

© 2013 Ken Howard, Southern Methodist University LoadedDie -loadedSide: int +LoadedDie() +getLoadedSide() : int +setLoadedSide(int):void +roll() : int TenSidedDie +TenSidedDie() +roll() : int +TenSidedDie() +roll() : int Die -faceValue: int +Die() +getFaceValue(): int +setFaceValue(int):void +roll():int +Die() +getFaceValue(): int +setFaceValue(int):void +roll():int Abstract Superclass Not instantiated. Superclass exists only to define common parts. Abstract Superclass Not instantiated. Superclass exists only to define common parts. RegularDie +RegularDie()

© 2013 Ken Howard, Southern Methodist University Die LoadedDie RegularDie TenSidedDie

© 2013 Ken Howard, Southern Methodist University Abstract and Concrete Classes Abstract class: Not instantiated. Superclass to define common parts. Concrete class: Instantiated.

© 2013 Ken Howard, Southern Methodist University Domain Modeling: Inheritance Generalizations should be discovered, not predicted. – In analysis, observe common relationships and common attributes. – In design, observe shared behavior for which delegation cannot be used to provide the common implementation. 100% Rule: All statements about the generalization are valid for the specialization. IF you keep Superclasses abstract, they’ll be more stable.

© 2013 Ken Howard, Southern Methodist University Die LoadedDie roll RegularDie

© 2013 Ken Howard, Southern Methodist University Is a… Animal Cat Dog “Bark” “” “Meow ” talk

© 2013 Ken Howard, Southern Methodist University ? talk

© 2013 Ken Howard, Southern Methodist University public abstract class Animal { public abstract String talk(); } public class Dog extends Animal { public String talk() { return “Yip!”; }

© 2013 Ken Howard, Southern Methodist University If I throw objects into a bag…

© 2013 Ken Howard, Southern Methodist University Domain Modeling: Inheritance

© 2013 Ken Howard, Southern Methodist University Polymorphism One request handled by receiver in different ways. - the requestor doesn’t have to get involved in details - the receiver does what it best knows how to do

© 2013 Ken Howard, Southern Methodist University Traditional handling approach with conditional logic: public Money getTotalPrice() { Money price; // calculate prices and tax … if (shipping.equals("Standard")) { price += //calculate standard shipping } else if (shipping.equals("Ground")) { price += //calculate ground shipping } else if (shipping.equals("Priority")) { price += //calculate ground shipping } // FIXME: support Int’l Shipping! return price; }

© 2013 Ken Howard, Southern Methodist University public Date getEstimatedDeliveryDate() { Date dueDate; if (shipping.equals("Standard")) { dueDate = //calculate standard shipping } else if (shipping.equals("Ground")) { dueDate = //calculate ground shipping } else if (shipping.equals("Priority")) { dueDate = //calculate ground shipping } // FIXME: support Courier return dueDate; }

© 2013 Ken Howard, Southern Methodist University What now?

© 2013 Ken Howard, Southern Methodist University Better? public Money getTotalPrice() { Money price; // calculate prices and tax … price += shippingStrategy.getShippingCost(weight, dimensions, destination); return price; } public Date getEstimatedDeliveryDate() { Date dueDate = shippingStrategy.getEstimatedDeliveryDate(); return dueDate; }

© 2013 Ken Howard, Southern Methodist University Polymorphism Example

© 2013 Ken Howard, Southern Methodist University Basic Inheritance Terminology Superclass Subclass Specialization Inheritance Class Hierarchy “Is a” (vs. “Has a”)

© 2013 Ken Howard, Southern Methodist University More Terminology The direct superclass is the superclass from which the subclass explicitly inherits. An indirect superclass is any class above the direct superclass in the class hierarchy. The Java class hierarchy begins with class Object (in package java.lang )  Every class in Java directly or indirectly extends (or “inherits from”) Object. Java supports only single inheritance, in which each class is derived from exactly one direct superclass.

© 2013 Ken Howard, Southern Methodist University Superclasses and Subclasses The figure below lists several simple examples of superclasses and subclasses  Superclasses tend to be “more general” and subclasses “more specific.” Because every subclass object is an object of its superclass, and one superclass can have many subclasses, the set of objects represented by a superclass is typically larger than the set of objects represented by any of its subclasses.

© 2013 Ken Howard, Southern Methodist University

Not every class relationship is an inheritance relationship. Has-a relationship (NOT INHERITANCE)  Create classes by composition of existing classes.  Example: Given the classes Employee, BirthDate and TelephoneNumber, it’s improper to say that an Employee is a BirthDate or that an Employee is a TelephoneNumber.  However, an Employee has a BirthDate, and an Employee has a TelephoneNumber.

© 2013 Ken Howard, Southern Methodist University Objects of all classes that extend a common superclass can be treated as objects of that superclass.  Commonality expressed in the members of the superclass. Inheritance issue  A subclass can inherit methods that it does not need or should not have.  Even when a superclass method is appropriate for a subclass, that subclass often needs a customized version of the method.  The subclass can override (redefine) the superclass method with an appropriate implementation.

© 2013 Ken Howard, Southern Methodist University Slot -amount : int +getScore():int SpinGame +SpinGame() +playGame():void +displayScore():void +SpinGame() +playGame():void +displayScore():void 10 1 GameTester +main(String[]):void slots 11 game Wheel +Wheel() +spin():int +Wheel() +spin():int theWheel 1 1 LoseSlot +getScore():int WinSlot +getScore():int BonusSlot +getScore():int

© 2013 Ken Howard, Southern Methodist University

protected Members A class’s public members are accessible wherever the program has a reference to an object of that class or one of its subclasses. A class’s private members are accessible only within the class itself. protected access is an intermediate level of access between public and private.  A superclass’s protected members can be accessed by members of that superclass, by members of its subclasses and by members of other classes in the same package protected members also have package access.  All public and protected superclass members retain their original access modifier when they become members of the subclass.

© 2013 Ken Howard, Southern Methodist University protected Members (Cont.) A superclass’s private members are hidden in its subclasses  They can be accessed only through the public or protected methods inherited from the superclass Subclass methods can refer to public and protected members inherited from the superclass simply by using the member names. When a subclass method overrides an inherited superclass method, the superclass method can be accessed from the subclass by preceding the superclass method name with keyword super and a dot (. ) separator.

© 2013 Ken Howard, Southern Methodist University Use of private with Inheritance Members of a subclass cannot access private members of its superclass. Preferred: Access the superclass attributes through methods in the superclass. Alternative: Declare superclass attributes as protected.

© 2013 Ken Howard, Southern Methodist University Student -studentNumber: int +Student() +Student(String,int) +getStudentNumber() : int +setStudentNumber(int):void +equalsl(Student) : boolean +toString() : String Person -name : String +Person() +Person(String) +getName(): String +setName(String):void +sameName(Person):boolean +toString():String +Person() +Person(String) +getName(): String +setName(String):void +sameName(Person):boolean +toString():String Another Example:

© 2013 Ken Howard, Southern Methodist University public class Person { private String name; public Person() { name = "No name yet."; } public Person(String initialName) { name = initialName; } public void setName(String newName) { name = newName; } Example: Base Class Base Class public String getName() { return name; } public toString () { return ”Person: " + name; } public boolean sameName(Person otherPerson) { return (this.name.equalsIgnoreCase(otherPerson. name)); }

© 2013 Ken Howard, Southern Methodist University Programming Example: Derived Class Derived Class public class Student extends Person { private int studentNumber; public Student() { super();//super is explained in a later section. studentNumber = 0;//Indicating no number yet } public Student(String initialName, int initialStudentNumber) { super(initialName); studentNumber = initialStudentNumber; } public int getStudentNumber() { return studentNumber; } public void setStudentNumber(int newStudentNumber) { studentNumber = newStudentNumber; } public String toStringt() { return super.toString() + ” Student Number : " + studentNumber; } public boolean equals(Student otherStudent) { return (this.sameName(otherStudent) && (this.studentNumber == otherStudent.studentNumber)); }

© 2013 Ken Howard, Southern Methodist University Programming Example: Test Class Test Class public class InheritanceDemo { public static void main(String[] args) { Student s = new Student(); s.setName("Warren Peace"); //setName is inherited from the class Person. s.setStudentNumber(2001); s.writeOutput(); } Screen Output Name: Warren Peace Student Number: 2001

© 2013 Ken Howard, Southern Methodist University Review… Private attributes cannot be accessed in subclass Private methods are not inherited Overloading: same method name, different parameters Overriding: same method signature implemented in a subclass

© 2013 Ken Howard, Southern Methodist University Also... Constructors are not inherited. The first task of a subclass constructor is to call its direct superclass’s constructor explicitly or implicitly  Ensures that the instance variables inherited from the superclass are initialized properly. If the code does not include an explicit call to the superclass constructor, Java implicitly calls the superclass’s default or no-argument constructor. A class’s default constructor calls the superclass’s default or no-argument constructor.

© 2013 Ken Howard, Southern Methodist University Inheriting from “Object” toString is one of the methods that every class inherits directly or indirectly from class Object.  Returns a String representing an object.  Called implicitly whenever an object must be converted to a String representation. Class Object ’s toString method returns a String that includes the name of the object’s class.  This is primarily a placeholder that can be overridden by a subclass to specify an appropriate String representation.

© 2013 Ken Howard, Southern Methodist University

protected members Using protected instance variables creates several potential problems. The subclass object can set an inherited variable’s value directly without using a set method.  A subclass object can assign an invalid value to the variable, possibly leaving the object in an inconsistent state. Subclass methods are more likely to be written so that they depend on the superclass’s data implementation.  Subclasses should depend only on the superclass services and not on the superclass data implementation.

© 2013 Ken Howard, Southern Methodist University

(C) 2010 Pearson Education, Inc. All rights reserved.

© 2013 Ken Howard, Southern Methodist University

public void foo() { foo(); doSomething(); doSomethingElse(); } public void foo() { super.foo(); doSomething(); doSomethingElse(); } VS.

© 2013 Ken Howard, Southern Methodist University 9.6 Constructors in Subclasses Instantiating a subclass object begins a chain of constructor calls  The subclass constructor, before performing its own tasks, invokes its direct superclass’s constructor If the superclass is derived from another class, the superclass constructor invokes the constructor of the next class up the hierarchy, and so on. The last constructor called in the chain is always class Object ’s constructor. Original subclass constructor’s body finishes executing last. Each superclass’s constructor manipulates the superclass instance variables that the subclass object inherits.

© 2013 Ken Howard, Southern Methodist University

Software Engineering with Inheritance When you extend a class, the new class inherits the superclass’s members—though the private superclass members are hidden in the new class. You can customize the new class to meet your needs by including additional members and by overriding superclass members.  Doing this does not require the subclass programmer to change (or even have access to) the superclass’s source code.  Java simply requires access to the superclass’s.class file.

© 2013 Ken Howard, Southern Methodist University Object Class All classes in Java inherit directly or indirectly from Object, so its 11 methods are inherited by all other classes. Figure 9.12 summarizes Object ’s methods. Can learn more about Object ’s methods in the online API documentation and in The Java Tutorial at : java.sun.com/javase- /6/docs/api/java/lang/Object.html or java.sun.com/docs/books/tutorial/java/IandI/ objectclass.html Every array has an overridden clone method that copies the array.  If the array stores references to objects, the objects are not copied—a shallow copy is performed. For more information about the relationship between arrays and class Object, see Java Language Specification, Chapter 10, at java.sun.com/docs/books/jls/third_edition/ html/arrays.html