Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline...

25
Chapter 8 Inheritance Part 2

Transcript of Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline...

Page 1: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

Chapter 8

Inheritance

Part 2

Page 2: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 2/23

Outline

Creating Subclasses

Overriding Methods

Class Hierarchies

Inheritance and Visibility

Designing for Inheritance

Page 3: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 3/23

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

Page 4: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 4/23

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

Page 5: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 5/23

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

Look at your JavaDoc to see the inheritance!

• 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

Page 6: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 6/23

The Object Class – Example: to String

• The Object class contains a few useful methods, which are inherited by all classes (which may/may not be overridden…)

• For example, the toString method is defined in the Object class

• Every time we define ‘our own’ toString method, we are actually overriding an inherited definition.

We have done this repeatedly in objects for which we want ‘certain’ attributes displayed simply by printing the object-only name.

By developing our own ‘toString()’ we can tailor the outputs to be exactly what we want and not use the default from Object.

So what happens if we System.out.println(objName) and don’t have a toString method in that object? Try it.

Page 7: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 7/23

The Object Class – Example: to String

• Note: the Object class is the prime class in the language.

• The toString method in the Object class (and it has one) is defined to return a string indicating the object’s class plus a few other goodies.

• This toString() method in Object is inherited (unless we override)

• Normally, when we want to print objects, we want certain attributes to be displayed and in formats that ‘we’ would like to see. Thus we frequently override the default toString() in Object and code our ‘own’ toString method in ‘our’ objects so that when we invoke it, it prints out what we want.

Page 8: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 8/23

The Object Class – Example: equals

• The equals method of the Object class returns true (Boolean) if two references are aliases (contain the same address)

• We can (and very often do) 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 exactly the same characters!

• The designers of the String class have overridden the equals method inherited from Object in favor of a more useful version that we normally use in comparing Strings.

Consequently, we use the overridden format with: int equals (object1.equals(object2))

Page 9: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 9/23

Abstract Classes

• An abstract class is a placeholder typically in a class hierarchy that represents a generic concept

An abstract class cannot be instantiated (that is, cannot make objects from it).

• We use the modifier abstract on the class header to declare a class as abstract:

public abstract class Product

{

// contents

}// end Product

Page 10: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 10/23

Abstract Classes and their Methods

• An abstract class often contains abstract methods that contain a method name with no definition (no body).

Classes that inherit will supply a body (later)

Unlike an interface, the abstract modifier (the tag) must be applied to each abstract method in an abstract class because an abstract class may also contain non-abstract methods (concrete methods) with full definitions.

So those methods that are abstract methods must be clearly defined to be abstract.

These may be well used in places where we plan on overriding its methods later…and we want a placeholder.)

Page 11: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 11/23

Abstract Classes and their Methods• Placeholders??? What??

• This means that some of its methods in an abstract class may be abstract and some may be concrete

• In an abstract class, we must tag a method as abstract, if it is abstract, as in: public abstract int myMethod (……)

• A class declared as abstract does not have to contain abstract methods – to make it abstract: simply declaring it abstract makes it so as in

public abstract GoofyClass.

But if it does have methods, those methods that are abstract must be declared to be abstract.

• There are some very important applications that use abstract classes!!

Page 12: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 12/23

Abstract Classes• The child of an abstract class must override all the abstract

methods of the parent, or it too will be considered abstract

So, if an abstract class contains abstract methods and possibly concrete methods), all the abstract methods must be overridden by a child, unless the child too is to be abstract.

Sometimes we have an inheritance hierarchy containing levels of abstract classes.

• Note: An abstract method cannot be defined as final or static, because it could not then be overridden.

Abstract methods are almost always overridden.

The use of abstract classes is an important element of software design – it allows us to establish common elements in a hierarchy that are too generic to instantiate

Think: calculate area of a geometric figure… (very general)

Could have this in a class GeometricObject. But if we had a method called computeArea(), the implementation of the method would be dependent upon lower level geometric classes that inherit this abstract method.

Page 13: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 13/23

{abstract} Geometric Figure

{abstract} int draw() ;

class Rectangle

draw()

class Circle

draw()

Class Trapezoid

draw()

Here, an inheritance hierarchy is set up. The derived classes all implement the abstract method, draw().There can be other ‘things’ in Geometric Figure, however, that are also inherited – not shown above.

How one draws a rectanble is differenent than drawing a circle.Yet, all of these have a draw() method!

Page 14: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 15/23

Outline

Creating Subclasses

Overriding Methods

Class Hierarchies

Inheritance and Visibility

Designing for Inheritance

Page 15: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 16/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 (if ‘protected,’ they could be).

• However, private members inherited by child classes exist and can be referenced indirectly through the methods of the parent. (and, I believe, you don’t need to create an object of the parent to use the parent’s method to access a private attribute, since you are inheriting from the parent.)

Confused? Remember: “pages” from 8.1 lecture was ‘protected.’ So it could be directly referenced in a child class. Private members in a base (parent) class can be accessed only via the methods in that base class.

Page 16: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 17/23

Visibility Revisited

• The parent can refer to its own private member directly (of course); 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

• Let’s look at three classes.

Page 17: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 18/23

//********************************************************************// FoodAnalyzer.java Author: Lewis/Loftus//// Demonstrates indirect access to inherited private members.//********************************************************************

public class FoodAnalyzer{ //----------------------------------------------------------------- // Instantiates a Pizza object and prints its calories per // serving. //----------------------------------------------------------------- public static void main (String[] args) { Pizza special = new Pizza (275); // creating an object of type Pizza

// with an argument passed to its// Constructor.

System.out.println ("Calories per serving: " + special.caloriesPerServing()); // presumably, method is in Pizza (or inherited by class Pizza…)

} // end main()} // end FoodAnalyzer

Page 18: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 19/23

//********************************************************************// Pizza.java Author: Lewis/Loftus//// Represents a pizza, which is a food item. Used to demonstrate// indirect referencing through inheritance.//********************************************************************

public class Pizza extends FoodItem Inherits from FoodItem{ //----------------------------------------------------------------- // Sets up a pizza with the specified amount of fat (assumes // eight servings). //----------------------------------------------------------------- public Pizza (int fatGrams) { super (fatGrams, 8); // invokes the parent’s Constructor!

// fatGrams is private in parent, but it is still inherited. // Get to it via ‘super’. If ‘protected’ in the parent (base class) it // could access directly.// Note also: no instance variables for any Pizza objects…

}// end Constructor} // end class// Note: caloriesPerServing() is NOT HERE. Thus it MUST be inherited. // Let’s see the base class.

Page 19: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 20/23

// FoodItem.java Author: Lewis/Loftus // Base Class// Represents an item of food. Used as parent of derived class to demonstrate indirect referencing.

public class FoodItem{ final private int CALORIES_PER_GRAM = 9; private int fatGrams; what is needed to access this guy? By whom? protected int servings; what is needed to access this guy? By whom?

// Sets up this food item with the specified number of fat grams public FoodItem (int numFatGrams, int numServings) { fatGrams = numFatGrams; // fatGrams is private. Can only access via methods servings = numServings; // servings is protected; could access directly due to inheritance. } // end Constructor

// Computes and returns the number of calories in this food item due to fat. private int calories() { return fatGrams * CALORIES_PER_GRAM; }// end calories()

// Computes and returns the number of fat calories per serving. public int caloriesPerServing() { return (calories() / servings); // this calls calories() (in same object) and divides by

// servings (a protected variable). }// end caloriesPerServing()}// end class FoodItem

Page 20: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 21/23

Outline

Creating Subclasses

Overriding Methods

Class Hierarchies

Inheritance and Visibility

Designing for Inheritance

Page 21: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 22/23

Designing for Inheritance

• As we've discussed, taking the time to create a good software design reaps long-term benefits

• Inheritance issues are an important part of an object-oriented design

• Properly designed inheritance relationships can contribute greatly to the elegance, maintainability, and reuse of the software

• Let's summarize some of the issues regarding inheritance that relate to a good software design

Page 22: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 23/23

Inheritance Design Issues

• Every derivation should be an is-a relationship

• Think about the potential future of a class hierarchy, and design classes to be reusable and flexible, and cohesive.

• Find common characteristics of classes and push them as high in the class hierarchy as appropriate

• Override methods as appropriate to tailor or change the functionality of a child

• Add new variables to children, but don't redefine (shadow) inherited variables

Page 23: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 24/23

Inheritance Design Issues - more

Allow each class to manage its own data;

Use the super reference to invoke the parent's constructor to set up its data

Even if there are no current uses for them, override general methods such as toString and equals with appropriate definitions

• Use abstract classes to represent general concepts that lower classes have in common

• Use visibility modifiers (private, protected, abstract, …) carefully to provide needed access without violating encapsulation

Page 24: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 25/23

Restricting Inheritance

• The final modifier can be used to curtail inheritance

• If the final modifier is applied to a method, then that method cannot be overridden in any descendent classes

• If the final modifier is applied to an entire class, then that class cannot be used to derive any children at all

Thus, an abstract class cannot be declared as final

• These are key design decisions, establishing that a method or class should be used as is

Page 25: Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.

© 2004 Pearson Addison-Wesley. All rights reserved 26/23

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