Chapter 8 Inheritance
Chapter 8 Inheritance
Animal
Book
protected int pages
+ getPages() : int
+ setPages(): void
Dictionary
+ getDefinitions() : int
+ setDefinitions(): void
+ computeRatios() : double
Example 2:
Example 3 on BOX
A Superclass Variable Can Reference a Subclass Object
• weightbox is a reference to
BoxWeight objects, and plainbox
is a reference to Box objects.
• Since BoxWeight is a subclass of
Box, it is permissible to assign
plainbox a reference to the
weightbox object
• when a reference to a subclass
object is assigned to a superclass
reference variable, you will have
access only to those parts of the
object defined by the superclass.
• This is why plainbox can’t access
weight even when it refers to a
A Superclass Variable Can Reference
a Subclass Object
• This makes sense, because the superclass has no knowledge of what a
subclass adds to it.
• This is why the last line of code in the preceding fragment is commented
out.
• It is not possible for a Box reference to access the weight field, because
Box does not define one.
Super Keyword
• In the preceding examples, classes derived from Box were not implemented as efficiently or as robustly as they
could have been.
• For example, the constructor for BoxWeight explicitly initializes the width, height, and depth fields of Box.
BoxWeight(double w, double h, double d, double m)
{
width = w;
height = h;
depth = d;
weight = m;
}
• Not only does this duplicate code found in its superclass, which is inefficient, but it implies that a subclass must
be granted access to these members.
• However, there will be times when you will want to create a superclass that keeps the details of its
implementation to itself (that is, that keeps its data members private).
• In this case, there would be no way for a subclass to directly access or initialize these variables on its own. Since
encapsulation is a primary attribute of OOP, it is not surprising that Java provides a solution to this problem.
• Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super
Example 1: Use of Super in
Constructor
• A subclass can call a constructor
defined by its superclass by use
of the following form of super:
• super(arg-list);
• Here, arg-list specifies any
arguments needed by the
constructor in the superclass.
• super( ) must always be the first
statement executed inside a
subclass’ constructor.
Example 2: User of Super to call the
member of its immediate superclass
• The second form of super acts
somewhat like this, except that it
always refers to the superclass of
the subclass in which it is used.
• This usage has the following
general form:
super.member
• Here, member can be either a
method or an instance variable.
When constructors are executed?
• For example, given a subclass called B
and a superclass called A, is A’s
constructor executed before B’s, or vice
versa?
• The answer is that in a class hierarchy,
constructors complete their execution
in order of derivation, from superclass
to subclass.
• since super( ) must be the first
statement executed in a
subclass’constructor, this order is the
same whether or not super( ) is used.
• If super( ) is not used,then the default
or parameterless constructor of each
superclass will be executed
Method
Overriding
• When a method in a subclass
has the same name and type
signature as a method in its
superclass, then the method in
the subclass is said to override
the method in the superclass.
• When an overridden method
is called from within its
subclass, it will always refer to
the version of that method
defined by the subclass.
• The version of the method
defined by the superclass will
be hidden.
How to also show superclass same
method?
Method
Overloading
• Method overriding
occurs only when the
names and the type
signatures of the two
methods are identical.
• If they are not, then the
two methods are simply
overloaded.
• For example, consider
this modified version of
the preceding example:
Overloading vs. Overriding
L 7.7
Dynamic Method Dispatch
• Previous examples in the preceding section demonstrate the mechanics of
method overriding, they do not show its power.
• Indeed, if there were nothing more to method overriding than a name space
convention, then it would be, at best, an interesting curiosity, but of little real
value.
• However, this is not the case.
• Method overriding forms the basis for one of Java’s most powerful concepts:
dynamic method dispatch.
• Dynamic method dispatch is the mechanism by which a call to an overridden
method is resolved at run time, rather than compile time.
• Dynamic method dispatch is important because this is how Java implements
run-time polymorphism
Dynamic Method Dispatch
• Let’s begin by restating an important principle: a superclass reference
variable can refer to a subclass object. Java uses this fact to resolve calls to
overridden methods at run time.
• When an overridden method is called through a superclass reference, Java
determines which version of that method to execute based upon the type of
the object being referred to at the time the call occurs.
• Thus, this determination is made at run time.
• When different types of objects are referred to, different versions of an
overridden method will be called.
• In other words, it is the type of the object being referred to (not the type of
the reference variable) that determines which version of an overridden
method will be executed
Dynamic Method Dispatch
• If a superclass contains a method that is overridden by a subclass, then when
different types of objects are referred to through a superclass reference
variable, different versions of the method are executed
Class Work on Dynamic Method
Dispatch
• The following program creates a superclass called Figure that stores the
dimensions of a two-dimensional object.
• It also defines a method called area( ) that computes the area of an object.
• The program derives two subclasses from Figure.
• The first is Rectangle and the second is Triangle.
• Each of these subclasses overrides area( ) so that it returns the area of a
rectangle and a triangle, respectively.
Solution:
Abstract Class
• There are situations in which you will want to define a superclass that
declares the structure of a given abstraction without providing a complete
implementation of every method.
• That is, sometimes you will want to create a superclass that only defines a
generalized form that will be shared by all of its subclasses, leaving it to
each subclass to fill in the details.
• Such a class determines the nature of the methods that the subclasses
must implement.
• One way this situation can occur is when a superclass is unable to create a
meaningful implementation for a method.
• This is the case with the class Figure used in the preceding example.
• The definition of area( ) is simply a placeholder. It will not compute and
display the area of any type of object.
Abstract Class (Cont..)
• You can require that certain methods be overridden by subclasses by specifying
the abstract type modifier.
• These methods are sometimes referred to as subclasser responsibility because
they have no implementation specified in the superclass.
• Thus, a subclass must override them—it cannot simply use the version defined in
the superclass.
• To declare an abstract method, use this general form:
abstract type name(parameter-list);
• As you can see, no method body is present.
• Any class that contains one or more abstract methods must also be declared
abstract.
• To declare a class abstract, you simply use the abstract keyword in front of the
class keyword at the beginning of the class declaration
Cautions on Abstract Class
• There can be no objects of an abstract class.
• That is, an abstract class cannot be directly instantiated with the new
operator.
• Such objects would be useless, because an abstract class is not fully defined.
• Also, you cannot declare abstract constructors, or abstract static methods.
• Any subclass of an abstract class must either implement all of the abstract
methods in the superclass, or be declared abstract itself
Previous Example Revisited with
Abstract Class
Three uses of Final Keyword
• Use 1: if you use final before an instance variable it works like a constant you can
not change the value in later methods.
• Use 2: To disallow a method from being overridden, specify final as a modifier at
the start of its declaration.
• Methods declared as final cannot be overridden. The following fragment
illustrates final:
class A { final void meth()
{
System.out.println("This is a final method.");
} }
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!"); } }
Three uses of Final Keyword (Cont..)
• Use 3: Sometimes you will want to prevent a class from being inherited. To do this,
precede the class declaration with final. Declaring a class as final implicitly declares
all of its methods as final, too.
• As you might expect, it is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its subclasses to provide
complete implementations.
• Here is an example of a final class:
final class A {
//...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
//...
}