Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8 Inheritance.

Similar presentations


Presentation on theme: "Chapter 8 Inheritance."— Presentation transcript:

1 Chapter 8 Inheritance

2 Inheritance Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class, or superclass, or base class The derived class is called the child class or subclass As the name implies, the child inherits characteristics of the parent That is, the child class inherits the methods and data defined by the parent class © 2004 Pearson Addison-Wesley. All rights reserved

3 Inheritance Inheritance relationships are shown in a UML class diagram using a solid arrow with an unfilled triangular arrowhead pointing to the parent class Vehicle Car Proper inheritance creates an is-a relationship, meaning the child is a more specific version of the parent © 2004 Pearson Addison-Wesley. All rights reserved

4 Inheritance A programmer can tailor a derived class as needed by adding new variables or methods, or by modifying the inherited ones Software reuse is a fundamental benefit of inheritance By using existing software components to create new ones, we capitalize on all the effort that went into the design, implementation, and testing of the existing software © 2004 Pearson Addison-Wesley. All rights reserved

5 Deriving Subclasses In Java, we use the reserved word extends to establish an inheritance relationship class Car extends Vehicle { // class contents } See Words.java (Chapter 9.1, page 472) See Book.java (Chapter 9.1, page 473) See Dictionary.java (Chapter 9.1, page 474) © 2004 Pearson Addison-Wesley. All rights reserved

6 The protected Modifier
Visibility modifiers affect the way that class members can be used in a child class Variables and methods declared with private visibility cannot be referenced by name in a child class They can be referenced in the child class if they are declared with public visibility -- but public variables violate the principle of encapsulation There is a third visibility modifier that helps in inheritance situations: protected © 2004 Pearson Addison-Wesley. All rights reserved

7 The protected Modifier
The protected modifier allows a child class to reference a variable or method directly in the child class It provides more encapsulation than public visibility, but is not as tightly encapsulated as private visibility A protected variable is visible to any class in the same package as the parent class The details of all Java modifiers are discussed in Appendix E Protected variables and methods can be shown with a # symbol preceding them in UML diagrams © 2004 Pearson Addison-Wesley. All rights reserved

8 Class Diagram for Words
Book # pages : int + pageMessage() : void Dictionary - definitions : int + definitionMessage() : void Words + main (args : String[]) : void © 2004 Pearson Addison-Wesley. All rights reserved

9 The super Reference Constructors are not inherited, even though they have public visibility Yet we often want to use the parent's constructor to set up the "parent's part" of the object The super reference can be used to refer to the parent class, and often is used to invoke the parent's constructor See Words2.java (Chapter 9.1, page 476) See Book2.java (Chapter 9.1, page 477) See Dictionary2.java (Chapter 9.1, page 478) © 2004 Pearson Addison-Wesley. All rights reserved

10 The super Reference A child’s constructor is responsible for calling the parent’s constructor The first line of a child’s constructor should use the super reference to call the parent’s constructor The super reference can also be used to reference other variables and methods defined in the parent’s class © 2004 Pearson Addison-Wesley. All rights reserved

11 Inheritance Example © 2004 Pearson Addison-Wesley. All rights reserved

12 Inheritance Hierarchy
© 2004 Pearson Addison-Wesley. All rights reserved

13 Multiple Inheritance Java supports single inheritance, meaning that a derived class can have only one parent class Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents Collisions, such as the same variable name in two parents, have to be resolved Java does not support multiple inheritance In most cases, the use of interfaces gives us aspects of multiple inheritance without the overhead © 2004 Pearson Addison-Wesley. All rights reserved

14 Overriding Methods A child class can override the definition of an inherited method in favor of its own The new method must have the same signature as the parent's method, but can have a different body The type of the object executing the method determines which version of the method is invoked See Messages.java (Chapter 9.2, page 481) See Thought.java (Chapter 9.2, page 482) See Advice.java (Chapter 9.2, page 483) © 2004 Pearson Addison-Wesley. All rights reserved

15 Overriding A method in the parent class can be invoked explicitly using the super reference If a method is declared with the final modifier, it cannot be overridden The concept of overriding can be applied to data and is called shadowing variables Shadowing variables should be avoided because it tends to cause unnecessarily confusing code © 2004 Pearson Addison-Wesley. All rights reserved

16 Overloading vs. Overriding
Overloading deals with multiple methods with the same name in the same class, but with different signatures Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature Overloading lets you define a similar operation in different ways for different parameters Overriding lets you define a similar operation in different ways for different object types © 2004 Pearson Addison-Wesley. All rights reserved

17 Class Hierarchies A child class of one parent can be the parent of another child, forming a class hierarchy Business KMart Macys ServiceBusiness Kinkos RetailBusiness © 2004 Pearson Addison-Wesley. All rights reserved

18 Class Hierarchies Two children of the same parent are called siblings
Common features should be put as high in the hierarchy as is reasonable An inherited member is passed continually down the line Therefore, a child class inherits from all its ancestor classes There is no single class hierarchy that is appropriate for all situations © 2004 Pearson Addison-Wesley. All rights reserved

19 © 2004 Pearson Addison-Wesley. All rights reserved

20 The Object Class A class called Object is defined in the java.lang package of the Java standard class library All classes are derived from the Object class If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class Therefore, the Object class is the ultimate root of all class hierarchies © 2004 Pearson Addison-Wesley. All rights reserved

21 The Object Class The Object class contains a few useful methods, which are inherited by all classes For example, the toString method is defined in the Object class Every time we define the toString method, we are actually overriding an inherited definition The toString method in the Object class is defined to return a string that contains the name of the object’s class along with some other information © 2004 Pearson Addison-Wesley. All rights reserved

22 The Object Class The equals method of the Object class returns true if two references are aliases We can override equals in any class to define equality in some more appropriate way As we've seen, the String class defines the equals method to return true if two String objects contain the same characters The designers of the String class have overridden the equals method inherited from Object in favor of a more useful version © 2004 Pearson Addison-Wesley. All rights reserved

23 Visibility Revisited It's important to understand one subtle issue related to inheritance and visibility All variables and methods of a parent class, even private members, are inherited by its children As we've mentioned, private members cannot be referenced by name in the child class However, private members inherited by child classes exist and can be referenced indirectly © 2004 Pearson Addison-Wesley. All rights reserved

24 Visibility Revisited Because the parent can refer to the private member, the child can reference it indirectly using its parent's methods The super reference can be used to refer to the parent class, even if no object of the parent exists See FoodAnalyzer.java (Chapter 9.4, page 490) See FoodItem.java (Chapter 9.4, page 491) See Pizza.java (Chapter 9.4, page 492) © 2004 Pearson Addison-Wesley. All rights reserved

25 Constructors in Inheritance
Do you have to provide a constructor for a class? No, a no-argument, default constructor is implicitly provided This default constructor calls the no-argument constructor of the super-class If super-class does not have no-argument version of the constructor A compilation error occurs Make sure there is such a constructor in the superclass What if there is no super-class? Object class is the implicit super-class, and it does have a no-argument constructor

26 Constructors What happens when no constructor is defined for a class?
 No-argument constructor will be provided implicitly for that class class C2 extends C1 { // no constructor is defined public C2() { // this constructor is super(); // automatically provided by Java. } If another constructor of the class is present, no-argument version of the constructor will not be provided automatically. CS102 Algorithims and Programming II

27 Constructors of Sub-Classes
The initialization of the fields of a sub-class consists of two phases: The initialization of the inherited fields The initialization of the fields that are declared in that sub-class. One of the constructors of the super-class must be invoked to initialize the fields inherited from the super-class. A super-class constructor must be invoked explicitly; Otherwise the no-argument constructor of the super-class will be automatically invoked This invocation must be the first statement of the constructor of the sub-class. (Or the one of the constructors of the sub-class must invoke another version of the constructor of that sub-class). CS102 Algorithims and Programming II

28 Constructors of Sub-Classes
class C1 { private int x; public C1() { x=0; } public C1(int xv) { x=xv; } } class C2 extends C1 { private int y; public C2(int xv, int yv) { super(xv); the constructor of the super-class is explicitly invoked y = yv; public C2(int yv) { this(1,yv); Another version of the constructor of this class is invoked public C2() { y = 2; No-argument version of the constructor of the super-class } } is implicitly invoked. super(); CS102 Algorithims and Programming II

29 Order of Initialization Step
The fields of the super-class are initialized using default values. One of the constructors of the super-class is executed. The fields of the extended class (sub-class) are initialized using the default values. One of the constructors of the extended class (sub-class) is executed. CS102 Algorithims and Programming II

30 Order of Initialization Step (cont.)
class C1 { private int x = 1; // executed first public C1() { x = 2; // executed second } class C2 extends C1 { private int y = 3; // executed third public C2() { super(); y = 4 ; // executed fourth CS102 Algorithims and Programming II

31 Abstract Classes An abstract class in a class hierarchy represents a generic concept Common elements in a hierarchy that are too generic to instantiate Cannot be instantiated abstract on the class header: public abstract class Product { // contents } © 2004 Pearson Addison-Wesley. All rights reserved

32 Abstract Classes abstract classes typically have:
abstract methods with no definitions (like an interface) probably also non-abstract methods with full definitions Does not have to contain abstract methods -- simply declaring it as abstract makes it so The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract © 2004 Pearson Addison-Wesley. All rights reserved

33 Abstract Classes abstract class A1 { abstract void m1();
abstract String m2(); } class C1 extends A1 { void m1() { System.out.println(“C1-m1”); } String m2() { return “C1-m2”; } abstract C2 extends A1 { void m1() { System.out.println(“C2-m1”); }  C2 must be abstract, because it does not implement the abstract method m2. CS102 Algorithims and Programming II

34 Abstract Classes Abstract methods cannot be defined as final or static
final cannot be overridden (contradiction!) static could be invoked by just using the name of the class – can’t invoke it with no implementation © 2004 Pearson Addison-Wesley. All rights reserved

35 Interfaces A Java interface is a collection of abstract methods and constants An abstract method is a method header without a method body abstract - but because all methods in an interface are abstract, usually it is left off An interface establishes a set of methods that a class will implement Similar to abstract class but all methods are abstract (and all properties are constant) © 2004 Pearson Addison-Wesley. All rights reserved

36 Interfaces interface I1 { Although we do not write here, it is assumed
that CONST1 is declared as a constant (with int CONST1=5; keywords public, final and static) void m1(); Although we do not write here, it is assumed } that m1 is declared with keywords public and abstract. Interface methods are public by default CS102 Algorithims and Programming II

37 Interfaces interface is a reserved word None of the methods in
an interface are given a definition (body) public interface Doable { public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num); } A semicolon immediately follows each method header © 2004 Pearson Addison-Wesley. All rights reserved

38 Interfaces Defines similarities that multiple classes share
to tie elements of several classes together - without having an inheritance relationship, so still no multiple inheritance separate design from coding An interface cannot be instantiated A class implements an interface by: stating so in the class header Implementing all abstract methods in the interface, plus maybe some others © 2004 Pearson Addison-Wesley. All rights reserved

39 Interfaces public class CanDo implements Doable {
public void doThis () // whatever } public void doThat () // etc. implements is a reserved word Each method listed in Doable is given a definition © 2004 Pearson Addison-Wesley. All rights reserved

40 Implementing Interfaces (cont.)
An interface can be implemented by multiple classes. Each implementing class can provide their own unique versions of the method definitions. interface I1 { void m1() ; } class C1 implements I1 { public void m1() { System.out.println(“Implementation in C1”); } class C2 implements I1 { public void m1() { System.out.println(“Implementation in C2”); } CS102 Algorithims and Programming II

41 © 2004 Pearson Addison-Wesley. All rights reserved

42 Interfaces A class can implement multiple interfaces
The interfaces are listed in the implements clause The class must implement all methods in all interfaces listed in the header class ManyThings implements interface1, interface2 { // all methods of both interfaces } © 2004 Pearson Addison-Wesley. All rights reserved

43 Implementing More Than One Interface
interface I1 { void m1(); } interface I2 { void m2() ; C must implement all methods in I1 and I2. void m3() ; class C implements I1, I2 { public void m1() { System.out.println(“C-m1”); } public void m2() { System.out.println(“C-m2”); } public void m3() { System.out.println(“C-m3”); } CS102 Algorithims and Programming II

44 Resolving Name Conflicts Among Interfaces
Since a class may implement more than one interface, the names in those interfaces may collide. To solve name collisions, Java use a simple mechanism. Two methods that have the same name will be treated as follows in Java: If they are different signature, they are considered to be overloaded. If they have the same signature and the same return type, they are considered to be the same method and they collapse into one. If they have the same signature and the different return types, a compilation error will occur. CS102 Algorithims and Programming II

45 Resolving Name Conflicts Among Interfaces
interface I1 { void m1(); void m2(); void m3(); } interface I2 { void m1(int a); There will be a compilation error for m3. int m3(); class C implements I1, I2 { public void m1() { … } // implementation of m1 in I1 public void m1(int x) { … } // implementation of m1 in I2 public void m2() { … } // implementation of m2 in I1 and I2 CS102 Algorithims and Programming II

46 Inheritance Relation Among Interfaces
Same as classes, interfaces can hold inheritance relation among them interface I2 extends I1 { … } Now, I2 contains all abstract methods of I1 plus its own abstract methods. The classes implementing I2 must implement all methods in I1 and I2. CS102 Algorithims and Programming II

47 Interfaces as Data Types
Interfaces (same as classes) can be used as data types. Different from classes: We cannot create an instance of an interface. interface I1 { … } class C1 implements I1 { … } class C2 extends C1 { … } // a variable can be declared as type I1 I1 x; A variable declared as I1, can store objects of C1 and C2. More later… CS102 Algorithims and Programming II

48 Interfaces The Java standard class library contains many helpful interfaces The Comparable interface contains one abstract method called compareTo, which is used to compare two objects We discussed the compareTo method of the String class in Chapter 5 The String class implements Comparable, giving us the ability to put strings in lexicographic order © 2004 Pearson Addison-Wesley. All rights reserved

49 The Comparable Interface
Any class can implement Comparable to provide a mechanism for comparing objects of that type if (obj1.compareTo(obj2) < 0) System.out.println ("obj1 is less than obj2"); The value returned from compareTo should be negative if obj1 is less that obj2, 0 if they are equal, and positive if obj1 is greater than obj2 When a programmer designs a class that implements the Comparable interface, it should follow this intent © 2004 Pearson Addison-Wesley. All rights reserved

50 The Comparable Interface
It's up to the programmer to determine what makes one object less than another For example, you may define the compareTo method of an Employee class to order employees by name (alphabetically) or by employee number The implementation of the method can be as straightforward or as complex as needed for the situation © 2004 Pearson Addison-Wesley. All rights reserved

51 The Iterator Interface
As we discussed in Chapter 5, an iterator is an object that provides a means of processing a collection of objects one at a time An iterator is created formally by implementing the Iterator interface, which contains three methods The hasNext method returns a boolean result – true if there are items left to process The next method returns the next object in the iteration The remove method removes the object most recently returned by the next method © 2004 Pearson Addison-Wesley. All rights reserved

52 The Iterator Interface
By implementing the Iterator interface, a class formally establishes that objects of that type are iterators The programmer must decide how best to implement the iterator functions Once established, the for-each version of the for loop can be used to process the items in the iterator © 2004 Pearson Addison-Wesley. All rights reserved

53 Interfaces You could write a class that implements certain methods (such as compareTo) without formally implementing the interface (Comparable) However, formally establishing the relationship between a class and an interface allows Java to deal with an object in certain ways Interfaces are a key aspect of object-oriented design in Java We discuss this idea further in Chapter 9 © 2004 Pearson Addison-Wesley. All rights reserved

54 When to use Abstract Methods & Abstract Class?
Abstract methods are usually declared where two or more subclasses are expected to fulfill a similar role in different ways through different implementations These subclasses extend the same Abstract class and provide different implementations for the abstract methods Use abstract classes to define broad types of behaviors at the top of an object-oriented programming class hierarchy, and use its subclasses to provide implementation details of the abstract class. © 2004 Pearson Addison-Wesley. All rights reserved

55 Why do we use Interfaces? Reason #1
To reveal an object's programming interface (functionality of the object) without revealing its implementation This is the concept of encapsulation The implementation can change without affecting the caller of the interface The caller does not need the implementation at the compile time It needs only the interface at the compile time During runtime, actual object instance is associated with the interface type © 2004 Pearson Addison-Wesley. All rights reserved

56 Why do we use Interfaces? Reason #2
To have unrelated classes implement similar methods (behaviors) One class is not a sub-class of another Example: Class Line and class MyInteger They are not related through inheritance You want both to implement comparison methods checkIsGreater(Object x, Object y) checkIsLess(Object x, Object y) checkIsEqual(Object x, Object y) Define Comparison interface which has the three abstract methods above © 2004 Pearson Addison-Wesley. All rights reserved

57 Why do we use Interfaces? Reason #3
To model multiple inheritance A class can implement multiple interfaces while it can extend only one class © 2004 Pearson Addison-Wesley. All rights reserved

58 Interface vs. Abstract Class
All methods of an Interface are abstract methods while some methods of an Abstract class are abstract methods Abstract methods of abstract class have abstract modifier An interface can only define constants while abstract class can have fields Interfaces have no direct inherited relationship with any particular class, they are defined independently Interfaces themselves have inheritance relationship among themselves © 2004 Pearson Addison-Wesley. All rights reserved

59 Problem of Rewriting an Existing Interface
Consider an interface that you have developed called DoIt: public interface DoIt { void doSomething(int i, double x); int doSomethingElse(String s); } Suppose that, at a later time, you want to add a third method to DoIt, so that the interface now becomes: boolean didItWork(int i, double x, String s); If you make this change, all classes that implement the old DoIt interface will break because they don't implement all methods of the interface anymore © 2004 Pearson Addison-Wesley. All rights reserved

60 Solution of Rewriting an Existing Interface
Create more interfaces later For example, you could create a DoItPlus interface that extends DoIt: public interface DoItPlus extends DoIt { boolean didItWork(int i, double x, String s); } Now users of your code can choose to continue to use the old interface or to upgrade to the new interface © 2004 Pearson Addison-Wesley. All rights reserved

61 When to use an Abstract Class over Interface?
For non-abstract methods, you want to use them when you want to provide common implementation code for all sub-classes Reducing the duplication For abstract methods, the motivation is the same with the ones in the interface – to impose a common behavior for all sub-classes without dictating how to implement it Remember a concrete can extend only one super class whether that super class is in the form of concrete class or abstract class © 2004 Pearson Addison-Wesley. All rights reserved

62 Summary Chapter 8 focused on:
deriving new classes from existing classes the protected modifier creating class hierarchies abstract classes indirect visibility of inherited members designing for inheritance © 2004 Pearson Addison-Wesley. All rights reserved


Download ppt "Chapter 8 Inheritance."

Similar presentations


Ads by Google