Transcript Chapter 3
Inheritance and Class Hierarchies
Chapter 3
Chapter Objectives
• To understand inheritance and how it facilitates code
reuse
• To understand how Java determines which method to
execute when there are multiple methods with the same
name in a class hierarchy
• To learn how to define and use abstract classes as base
classes in a hierarchy
• To study class Object and its methods and to learn how
to override them
• To learn how to “clone” an object and to understand the
difference between a true clone (deep copy) and a
shallow copy
Chapter 3: Inheritance and Class Hierarchies
2
Chapter Objectives (continued)
• To understand why Java does not implement multiple
inheritance and to see how you can gain some of the
advantages of multiple inheritance through interfaces
and delegation
• To become familiar with a class hierarchy for drawable
shapes
• To be introduced to an object factory and to learn how to
use it
• To understand how to create packages and to learn
more about visibility
Chapter 3: Inheritance and Class Hierarchies
3
Introduction to Inheritance and Class
Hierarchies
• Popularity of OOP is that it enables programmers to
reuse previously written code saved as classes
• All Java classes are arranged in a hierarchy, starting with
Object, which is the superclass of all Java classes
• Inheritance in OOP is analogous to inheritance in
humans
• Inheritance and hierarchical organization allow you to
capture the idea that one thing may be a refinement or
extension of another
Chapter 3: Inheritance and Class Hierarchies
4
Chapter 3: Inheritance and Class Hierarchies
5
Is-a Versus Has-a Relationships
• One misuse of inheritance is confusing the has-a
relationship with the is-a relationship
• The has-a relationship means that one class has the
second class as an attribute
• We can combine is-a and has-a relationships
• The keyword extends specifies that one class is a
subclass of another
Chapter 3: Inheritance and Class Hierarchies
6
A Superclass and a Subclass
• Consider two classes: Computer and Laptop
• A laptop is a kind of computer and is therefore a
subclass of computer
Chapter 3: Inheritance and Class Hierarchies
7
Initializing Data Fields in a Subclass and the
No-Parameter Constructor
• Private data fields belonging to a base class must be
initialized by invoking the base class’s constructor with
the appropriate parameters
• If the execution of any constructor in a subclass does not
invoke a superclass constructor, Java automatically
invokes the no-parameter constructor for the superclass
• Initializes that part of the object inherited from the
superclass before the subclass starts to initialize its
part of the object
Chapter 3: Inheritance and Class Hierarchies
8
Protected Visibility for Superclass Data
Fields
• Private data fields are not accessible to derived classes
• Protected visibility allows data fields to be accessed
either by the class defining it or any subclass
• In general, it is better to use private visibility because
subclasses may be written by different programmers and
it is always good practice to restrict and control access to
the superclass data fields
Chapter 3: Inheritance and Class Hierarchies
9
Method Overriding
• If a derived class has a method found
within its base class, that method will
override the base class’s method
• The keyword super can be used to gain
access
to
superclass
methods
overridden by the base class
• A subclass method must have the same
return type as the corresponding
superclass method
Chapter 3: Inheritance and Class Hierarchies
10
Method Overloading
• Method overloading: having multiple methods with the
same name but different signatures in a class
• Constructors are often overloaded
• Example:
• MyClass(int inputA, int inputB)
• MyClass(int inputA, int inputB, double inputC)
Chapter 3: Inheritance and Class Hierarchies
11
Polymorphism
• A variable of a superclass type can reference an object
of a subclass type
• Polymorphism means many forms or many shapes
• Polymorphism allows the JVM to determine which
method to invoke at run time
• At compile time, the Java compiler can’t determine what
type of object a superclass may reference but it is known
at run time
Chapter 3: Inheritance and Class Hierarchies
12
Abstract Classes, Assignment, and Casting
in a Hierarchy
• An interface can declare methods but does not provide
an implementation of those methods
• Methods declared in an interface are called abstract
methods
• An abstract class can have abstract methods, data
fields, and concrete methods
• Abstract class differs from a concrete class in that
• An abstract class cannot be instantiated
• An abstract class can declare abstract methods,
which must be implemented in its subclasses
Chapter 3: Inheritance and Class Hierarchies
13
Abstract Classes and Interfaces
• Like an interface, an abstract class can’t be instantiated
• An abstract class can have constructors to initialize its
data fields when a new subclass is created
• Subclass uses super(…) to call the constructor
• May implement an interface but it doesn’t have to define
all of the methods declared in the interface
• Implementation is left to its subclasses
Chapter 3: Inheritance and Class Hierarchies
14
Abstract Class Number and the Java
Wrapper Classes
Chapter 3: Inheritance and Class Hierarchies
15
Summary of Features of Actual Classes,
Abstract Classes, and Interfaces
Chapter 3: Inheritance and Class Hierarchies
16
Class Object, Casting and Cloning
• Object is the root of the class hierarchy; every class has
Object as a superclass
• All classes inherit the methods defined in class Object
but may be overridden
Chapter 3: Inheritance and Class Hierarchies
17
The Method toString
• You should always override the toString method if you
want to represent an object’s state
• If you do not override it, the toString method for class
Object will return a string…just not the string you want or
are expecting
Chapter 3: Inheritance and Class Hierarchies
18
Operations Determined by Type of
Reference Variable
• A variable can reference an object whose type is a
subclass of the variable type
• The type of reference, not the type of the object
referenced, determines what operations can be
performed
• Java is a strongly typed language so the compiler always
verifies that the type of the expression being assigned is
compatible with the variable type
Chapter 3: Inheritance and Class Hierarchies
19
Casting in a Class Hierarchy
• Java provides casting to enable us to process one object
referenced by one type through a reference variable of
its actual type
• Casting does not change the object referenced; it
creates an anonymous reference to that object
• Downcast: cast a higher type to a lower type
• The
instanceof
operator
can
guard
against
ClassCastException errors
• You can downcast an interface reference to the specific
implementation type
Chapter 3: Inheritance and Class Hierarchies
20
Java 5.0 Reduces Need for Casting
• Two new features that reduce the need for casting:
• Autoboxing/unboxing
• Generics
• Autoboxing/unboxing eases the conversion between a
primitive type and its corresponding wrapper type
Chapter 3: Inheritance and Class Hierarchies
21
The Method Object.equals
• The Object.equals method has a parameter of type
Object
• Compares two objects to determine whether they are
equal
• You must override the equals method if you want to be
able to compare two objects of a class
Chapter 3: Inheritance and Class Hierarchies
22
Cloning
• The purpose of cloning in object-oriented programming
is analogous to cloning in biology
• Create an independent copy of an object
• Initially, both objects will store the same information
• You can change one object without affecting the other
• Will cause both e1.name and e2.name to reference “Jim”
Chapter 3: Inheritance and Class Hierarchies
23
The Shallow Copy Problem
Chapter 3: Inheritance and Class Hierarchies
24
• The statement e1.setAddressLine1("Room 224");
creates a new String object that is referenced by
e1.address.line1 and e2.address.line1
Chapter 3: Inheritance and Class Hierarchies
25
The Object.clone method
• Java provides the Object.clone method to help solve the
shallow copy problem
• The initial copy is a shallow copy as the current object’s
data fields are copied
• To make a deep copy, you must create cloned copies of
all components by invoking their respective clone
methods
Chapter 3: Inheritance and Class Hierarchies
26
The Object.clone method (continued)
• After e1.setAddressLine1("Room 224"); only
e1.address.line1 references the new String object.
Chapter 3: Inheritance and Class Hierarchies
27
Employee.clone()
Chapter 3: Inheritance and Class Hierarchies
28
Address.clone()
Chapter 3: Inheritance and Class Hierarchies
29
Multiple Inheritance, Multiple Interfaces, and
Delegation
• Multiple inheritance: the ability to extend more than one
class
• Multiple inheritance is a language feature that is difficult
to implement and can lead to ambiguity
• Therefore, Java does not allow a class to extend
more than one class
Chapter 3: Inheritance and Class Hierarchies
30
Using Multiple Interfaces to Emulate Multiple
Inheritance
• If we define two interfaces, a class can implement both
• Multiple interfaces emulate multiple inheritance
Chapter 3: Inheritance and Class Hierarchies
31
Using Multiple Interfaces to Emulate Multiple
Inheritance (continued)
Chapter 3: Inheritance and Class Hierarchies
32
Implementing Reuse Through Delegation
• You can reduce duplication of modifications and reduce
problems associated with version control through a
technique known as delegation
• In delegation, a method of one class accomplishes an
operation by delegating it to a method of another class
Chapter 3: Inheritance and Class Hierarchies
33
Packages
• The Java API is organized into packages
• The package to which a class belongs is declared by the
first statement in the file in which the class is defined
using the keyword package followed by the package
name
• All classes in the same package are stored in the same
directory or folder
• All the classes in one folder must declare themselves to
be in the same package
• Classes that are not part of a package may access only
public members of classes in the package
Chapter 3: Inheritance and Class Hierarchies
34
The No-Package-Declared Environment and
Package Visibility
• There exists a default package
• Files that do specify a package are considered part of
the default package
• If you don’t declare packages, all of your packages
belong to the same, default package
• Package visibility sits between private and protected
• Classes, data fields, and methods with package visibility are
accessible to all other methods of the same package but are
not accessible to methods outside of the package
• Classes, data fields, and methods that are declared
protected are visible to all members of the package
Chapter 3: Inheritance and Class Hierarchies
35
Visibility Supports Encapsulation
• The rules for visibility control how encapsulation occurs
in a Java program
• Private visibility is for members of a class that should not
be accessible to anyone but the class, not even the
classes that extend it
• Package visibility allows the developer of a library to
shield classes and class members from classes outside
the package
• Use of protected visibility allows the package developer
to give control to other programmers who want to extend
classes in the package
Chapter 3: Inheritance and Class Hierarchies
36
Visibility Supports Encapsulation (continued)
Chapter 3: Inheritance and Class Hierarchies
37
A Shape Class Hierarchy
Chapter 3: Inheritance and Class Hierarchies
38
A Shape Class Hierarchy (continued)
Chapter 3: Inheritance and Class Hierarchies
39
Chapter 3: Inheritance and Class Hierarchies
40
A Shape Class Hierarchy (continued)
Chapter 3: Inheritance and Class Hierarchies
41
Object Factories
• An object factory is a method that creates instances of
other classes
• Object factories are useful when:
• The necessary parameters are not known or must be
derived via computation
• The appropriate implementation of an interface or
abstract class should be selected as the result of
some computation
Chapter 3: Inheritance and Class Hierarchies
42
Object Factories (continued)
Chapter 3: Inheritance and Class Hierarchies
43
Chapter Review
• Inheritance and class hierarchies to capture the idea that
one thing may be a refinement or extension of another
• Encapsulation and inheritance impose structure on
object abstractions
• The keyword interface defines an interface
• The keyword abstract defines an abstract class or
method
• Delegation gains some of the advantages of multiple
inheritance
• Visibility is influenced by the package in which a class is
declared
Chapter 3: Inheritance and Class Hierarchies
44
Screenshots and code –one of the
DrawableShape classes
public class DrawableTriangle
extends DrawableShape {
public DrawableTriangle(int bas, int hei,
Point poi, Color border, Color inter) {
super(poi, border, inter, new RtTriangle(bas, hei));
}
// Methods
/** Draw the triangle using the given graphics context.
@param g The graphics context
*/
public void drawMe(Graphics g) {
Polygon rtTri = new Polygon();
RtTriangle triangle = (RtTriangle) theShape;
rtTri.addPoint(pos.x, pos.y);
rtTri.addPoint(pos.x, pos.y - triangle.getHeight());
rtTri.addPoint(pos.x + triangle.getBase(), pos.y);
g.setColor(interiorColor);
g.fillPolygon(rtTri);
g.setColor(borderColor);
g.drawPolygon(rtTri); }
/** Return a string representation of the triangle.
@return A string representation of the triangle
*/
public String toString() {
return "Drawable " + theShape + super.toString(); }}
Chapter 3: Inheritance and Class Hierarchies
45
The test program opens a frame and draws
on a panel
Chapter 3: Inheritance and Class Hierarchies
46