ObjectOriented Programming Inheritance CSE 1341 2013 Ken Howard
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 Office Cathedral © 2013 Ken Howard, Southern Methodist University Residence School
Die Regular. Die -face. Value: int +Regular. Die() +get. Face. Value(): int +set. Face. Value(int): void +roll(): int A die component: • Has a face value. • Can roll itself — “Do It Myself. ” © 2013 Ken Howard, Southern Methodist University
Extending the Die Class Loaded. Die • Objects (software components) can have variations on a theme. • Consider a new kind of Die, Loaded. Die, that can remember a loaded side and set the value of half of the rolls to the loaded. Side. © 2013 Ken Howard, Southern Methodist University -face. Value: int -loaded. Side: int +Loaded. Die() +get. Face. Value(): int +set. Face. Value(int): void +get. Loaded. Side() : int +set. Loaded. Side(int): void +roll(): int
Die and Loaded. Die: Common Parts Loaded. Die Regular. Die -face. Value: int +Regular. Die() +get. Face. Value(): int +set. Face. Value(int): void +roll(): int © 2013 Ken Howard, Southern Methodist University -face. Value: int -loaded. Side: int +Loaded. Die() +get. Face. Value(): int +set. Face. Value(int): void +get. Loaded. Side() : int +set. Loaded. Side(int): void +roll(): int
Inheritance Regular. Die -face. Value: int inherited +Regular. Die() +get. Face. Value(): int +set. Face. Value(int): void +roll(): int Superclass Subclass Loaded. Die -loaded. Side: int added over-ridden +Loaded. Die() +get. Loaded. Side() : int +set. Loaded. Side(int): void +roll() : int © 2013 Ken Howard, Southern Methodist University
Inheritance • Inheritance: – Is present when software classes are organized in a generalizationspecialization hierarchy. inherited – 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 added (redefine) an inherited method. over-ridden • Advantages? © 2013 Ken Howard, Southern Methodist University Regular. Die -face. Value: int +Die() +get. Face. Value(): int +set. Face. Value(int): void +roll(): int Loaded. Die -loaded. Side: int +Loaded. Die() +get. Loaded. Side() : int +set. Loaded. Side(int): void +roll() : int
Polymorphism Regular. Die • Polymorphism means: – The same message can be interpreted in different ways, depending on the receiver. roll() – 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? © 2013 Ken Howard, Southern Methodist University roll() Loaded. Die
Abstract Superclass • Not instantiated. • Superclass exists only to define common parts. Die -face. Value: int +Die() +get. Face. Value(): int +set. Face. Value(int): void +roll(): int Regular. Die Ten. Sided. Die Loaded. Die -loaded. Side: int +Regular. Die() +Ten. Sided. Die() +roll() : int © 2013 Ken Howard, Southern Methodist University +Loaded. Die() +get. Loaded. Side() : int +set. Loaded. Side(int): void +roll() : int
Die Regular. Die Loaded. Die Ten. Sided. Die © 2013 Ken Howard, Southern Methodist University
Abstract and Concrete Classes Abstract class: • Not instantiated. • Superclass to define common parts. © 2013 Ken Howard, Southern Methodist University Concrete class: Instantiated.
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 roll Regular. Die Loaded. Die © 2013 Ken Howard, Southern Methodist University
Is a… Animal “” talk Dog “Bark” Cat “Meow” © 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 get. Total. Price() { 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
Traditional handling approach with conditional logic: public Date get. Estimated. Delivery. Date() { Date due. Date; if (shipping. equals("Standard")) { due. Date = //calculate standard shipping } else if (shipping. equals("Ground")) { due. Date = //calculate ground shipping } else if (shipping. equals("Priority")) { due. Date = //calculate ground shipping } // FIXME: support Courier } return due. Date; © 2013 Ken Howard, Southern Methodist University
What now? © 2013 Ken Howard, Southern Methodist University
Better? public Money get. Total. Price() { Money price; // calculate prices and tax … price += shipping. Strategy. get. Shipping. Cost(weight, dimensions, } return price; destination); public Date get. Estimated. Delivery. Date() { Date due. Date = } shipping. Strategy. get. Estimated. Delivery. Date(); return due. Date; © 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
Game. Tester Wheel Spin. Game 1 1 game +main(String[]): void 1 1 the. Wheel +Wheel() +spin(): int +Spin. Game() +play. Game(): void +display. Score(): void slots 1 10 Slot -amount : int +get. Score(): int Bonus. Slot +get. Score(): int © 2013 Ken Howard, Southern Methodist University Win. Slot +get. Score(): int Lose. Slot +get. Score(): 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
Another Example: Person -name : String +Person() +Person(String) +get. Name(): String +set. Name(String): void +same. Name(Person): boolean +to. String(): String Student -student. Number: int +Student() +Student(String, int) +get. Student. Number() : int +set. Student. Number(int): void +equalsl(Student) : boolean +to. String() : String © 2013 Ken Howard, Southern Methodist University
Example: public class Person { private String name; public Person() { name = "No name yet. "; } public Person(String initial. Name) { name = initial. Name; } public void set. Name(String new. Name) { name = new. Name; } © 2013 Ken Howard, Southern Methodist University Base Class public String get. Name() { return name; } public to. String () { return ”Person: " + name; } public boolean same. Name(Person other. Person) { return (this. name. equals. Ignore. Case(other. Person. name)); } }
Programming Example: Derived Class public class Student extends Person { private int student. Number; public Student() { super(); //super is explained in a later section. student. Number = 0; //Indicating no number yet } public Student(String initial. Name, int initial. Student. Number) { super(initial. Name); student. Number = initial. Student. Number; } public int get. Student. Number() { return student. Number; } public void set. Student. Number(int new. Student. Number) { student. Number = new. Student. Number; } public String to. Stringt() { return super. to. String() + ” Student Number : " + student. Number; } public boolean equals(Student other. Student) { return (this. same. Name(other. Student) && (this. student. Number == other. Student. student. Number) } } © 2013 Ken Howard, Southern Methodist University
Programming Example: public class Inheritance. Demo { public static void main(String[] args) { Student s = new Student(); s. set. Name("Warren Peace"); //set. Name is inherited from the class Person. s. set. Student. Number(2001); s. write. Output(); } } Screen Output Name: Warren Peace Student Number: 2001 © 2013 Ken Howard, Southern Methodist University Test Class
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” • to. String 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 to. String 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
© 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
© 2013 Ken Howard, Southern Methodist University
© 2013 Ken Howard, Southern Methodist University (C) 2010 Pearson
© 2013 Ken Howard, Southern Methodist University
© 2013 Ken Howard, Southern Methodist University
© 2013 Ken Howard, Southern Methodist University
© 2013 Ken Howard, Southern Methodist University
© 2013 Ken Howard, Southern Methodist University
© 2013 Ken Howard, Southern Methodist University
public void foo() { foo(); do. Something(); do. Something. Else(); } © 2013 Ken Howard, Southern Methodist University VS. public void foo() { super. foo(); do. Something(); do. Something. Else(); }
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
© 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/Iand. I/ 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 © 2013 Ken Howard, Southern Methodist University
- Slides: 55