Java Module-3 Part -A(Inheritance )Book Notes
Java Module-3 Part -A(Inheritance )Book Notes
Inheritance
Inheritance Basics
To inherit a class, you simply incorporate the definition of oneclass intoanotherby
using
thejextendslkeyword.To see how, let's begin with a short example. The following
program
creates a superclass called A and a subclass called B.Notice how the keyword extends is
used to create a subclass of A.
1/Create a superclass.
class A
int i, ji
void showij () {
System.out.println ("i and j: "+ i + " n + i):
void showk () (
System.out.println ("k: "+ k);
void sum () {
System. out.print ln ("i+j+k: "+ (i+j+k) );
157
158 Part I: The Java Language
class SimpleInheritance
public static void main (String
args () ){
A superob = new A():
B subob = new B()}
Contents of superOb:
i and j: 10 20
Contents of subob:
i and j: 7 8
k: 9
why subObcan access i and jand call showij(). Also, inside sum(), and
i j can bereferred
to directly, as if they were part of B.
Even though is a superclass for B, it is also a completelyindependent, stand-alone
class. Being a superclass for a subclas does not mean that the superclass cannot be used
by itself. Further, a subclass can be a superclass for another subclass.
The general form of
a class declaration that inherits a superclass is shownhere:
//body of class
Chapter 8: Inheritance 159
I
superclass of itself.
Create a superclass.
/
class A{
int i; //public by default
private int j // private to A
class Access {
public static void main (String args (] )
{
B subOb = new B();
subob. sum() ;
System. out.println ("Total is " + subOb. total) ;
Thisprogram will not compile because the reference to jinside the sum()method of B
causes an access violation. Since j is declared as private, it is only accessible by other members
of its own class. Subclasses have no access to it.
Chapter 8: Inheritance 163
Using super
In the preceding examples,
classes derived from Box were not
as robustly as they could have been,For implemented as efficiently or
example,the constructor for
initializes the width, height, BoxWeight explicitly
and depth fields of Box(). Not only
tound in its superclass, which is does this duplicate code
inefficient,but it implies that a PARTI
subclass must be granted access
to these members.
However.(there will be times when you
will want to create a superclass
keeps the details of its implementation that
to itself (that is,that keeps its data
In this case, there would be no way members private).
for a subclass to directly access or
initialize these variables
on its ownSince 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
super(arg-list);
Here,arg-list specifies any arguments needed by the constructor in the superclass. super()
must always be the first statementexecuted inside a subclass' constructor.
To see how super() is used,consider this improved version of the BoxWeight() class:
Here,BoxWeight( ) calls super() with the arguments w,h,and d. This causes the Box()
constructor to be called, which initializes width, height, and depth using these values.
BoxWeight nolonger initializes these values itself. It only needs to initialize the value unique
to it: weight. This leaves Box free to make these values private if desired.
In the preceding example,super( )was called with three arguments.Since constructors
)
can be overloaded,super( can be called using any form defined by the superclass. The
constructorexecuted will be the one that matches the arguments. For example, here is a
complete implementation of BoxWeight that provides constructors for the various ways
Chapter 8: Inheritance 167
B(int a, int b) {
super. i - a; I/i
i = b; // i in B
in A I
PART
void show () {
System. out.println("i in superclass: + super.i);
System.out.println ("i in subclass: + i) ;
class UseSuper {
public static void main (Stringargs (]) {
subob, show ()
i in superclass: 1
i in subclass: 2
Although the instance variable i in B hides the i in A, superallows access to the i defined
in the superclass. As you will see,super can also be used to call methods that are hidden by a
subclass.
For example, given three classes called A, andC,C can be a subclass of B, which is a
B,
subclass of A. When this type of situation occurs, each subclass inherits allof the traits
found in all of its superclasses. In this case, C inherits all aspects of B and A. To see how
amultilevel hierarchy can be useful, consider the following program. In it, the subclass
BoxWeight is used as a superclass to create the subclass called Shipment. Shipment inherits
all of the traits of BoxWeight and Box, and adds a field called cost, which holds the
cost of
// Add weight.
class BoxWeight extends Box
{
double weight; // weight of£ box
1/ default constructor
BoxWeight () {
Super(0;
weight = -1;
Chapter 8: In heritance 169
PARTI
{
double cost;
// default constructor
Shipment () {
super );
cost = -l;
super(len, m);
Cost = C;
class DemoShipment {
public static void main (String args []) {
Shipment shipment1 =
new Shipment (10, 20, 15, 10, 3.41);
Shipment shipment2 =
new Shipment (2, 3, 4, 0.76, 1.28);
double vol;
vol = shipmentl.volume () :
System.out.println("Volume of shipment1 is " + vol) :
System., out.println ("Weight of shipment1 is "
+ shipment1.weight)
;
System.out.println ("Shipping cost: $" + shipmentl. cost);
System.out.println() ;
170 Part I: The Java Langu age
vol =
shipment2.volume ()
System. out.println ("Volume of
shipment2 is " + vol);
System.out.println("Neight of shipment2 is "
+ shipment2. weight)
System.out.print ln("Shipping cost: $" + shipment2. cost)i
constructor requires parameters,then all subclasses must pass those parameters "up the
line." This is true whether or not a subclass needs parameters of its own.
shown all in one file. This is for your convenience only. In Java, all three classes
Shipment, is
could have ben placed into their own filesand compiled separately. In fact, using separate
the hierarchy called? For example, given a subclass called B and a superclass called A, is A's
constructors
called before B's, or vice versa? The answer
is that in a class hierarchy,
constructor
of derivation, from superclass to subclass. Further, since super( ) must be the
are called in order
first statement executed ina subclass' constructor, this order is the same whether or not super()
)is not used, then the default or parameterless constructor of each superclass
is used. If super(
program illustrates when constructors are executed:
will be executed. The following
class B extends A
{
B) {
constructor. ");
System. out.println ("Ingide B's
PARTI
class C extends B
C)
{
");
System.out.println ("Inside C's constructor.
class CallingCons
public static void main(String args []){
Cc = new C();
in order of derivation.
As you can see, the constructors are called
Because a superclass has no knowledge of any subclass, any initialization it needs to perform
is separate from and possibly prerequisite to any initialization performed by the subclass.
Method 0verriding
In aclass hierarchy, when a method
in a subclass has the same name and type signature as
a method in its method in the subclass is said to override the method in
superclass, then the
the superclass. When an overriddenmethod is called from within a subclass, it will always
refer to the version of that method defined by the subclass. The version of the method defined
//Method overriding.
class A{
int i, j:
A(int a, int b) {
i = a;
j = b;
// display i and j
void show ()
{
System.out.println ("i and j: " + i + " n + i);
172 Part I: The Java
Language
class B extends
int k;
A{
// display k - this
void show (){ overrides show () in A
class Override {
public static void main (String
B subOb = new B(1, 2, args [)){
3) ;
class B extends A {
int k;
Ifyou substitute this version of A into the previousprogram, you will see the following
output:
i and j: 1 2
k: 3
is
which version of that method to execute based upon thetype 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 ofthe object being referred to (notthe type of the reference variable)
class B extends A {
//override callme ()
Sub 1 class
void callme () {
System.out.println("Inside B's callme method"):
h:-Hierica
Tnhetance
class C extends A {
1/override callme ()
void callme () {
System.out.println ("Inside C's callme method"):
class Dispatch {
public static void main (String args [] ) (
r= c; // r refers to a c object
r.callme(); // calls C's version of£ callme
This program creates one superclass called A and two subclasses of it, called B and C.
Subclasses B and C override callme() declared in A.Inside the main() method,objects of
type A, B, and C are declared. Also, a reference of type A,called r, is declared. Theprogram
then in turn assigns a reference to each type of object to r and uses that reference to invoke
callme( ). As the output shows,the version of callme( )executed is determined by the type
of object being referred to at the time of the call. Had it been deternmined by the type of the
reference variable, r, you would seethree calls to A's callme( method. )
NoTE Readers familiar with C++ or C# will recognize that overridden methods in Java are similar
to virtual functions in those languages.
1/ Using run-time
polymorphism.
class Figure
double diml;
double dim2;
double area(){
System. out.println ("Area for Figure is undefined. ");
return 0;
class FindAreas {
public static void main (String args []) {
Figure f = new Figure (10, 10) ;
Rectangle r = new Rectangle (9, 5);
Triangle t = new Triangle (10, 8);
Chapter 8: Inheritance 177
Figure figref;
figref = r;
()) ;
System.out .print ln ("Area is " + £igref.area
figref = t;
System.out .println("Area is " + figref. area () );
I
PART
figref = f;
System.out .println("Area is "+ figref.area ());
todefine one consistent interface that is used by several different, yet related, types of objects.
In this case, if an object is derived from Figure, then its area can be obtained by calling area( ).
The interface to this operationis the sameno matter what type of figure is being used.
will be shared by all of its subclasses, leaving it to each subclass to fill in thedetails. Such a
class determines the nature of the methods that the subclasses must implemernt. Oneway
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
override all necessary methods. Java's solution to this problem is the abstract method.
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
178 Part I: The Java Language
override themit cannot simply use the version defined in the superclass. To declare an
abstract method, use this general form:
class B extends A {
void callme () {
System.out.println ("B's implementation of callme. ");
class AbstractDemo {
public static void main (String args []) {
Bb = new B() ;
b.callme () ;
b.callmetoo ();
Notice that no objects of class A are declared in the program. As mentioned, it is not
possible an abstract class. One other point:
to instantiate class A implements a concrete
method called callmetoo(). This is perfectly acceptable. Abstract classes can include as
much implementation as they see fit.
Although abstract classes cannot be used can be used to create
to instantiate objects, they
Using an abstract class, you can improve the Figure class shownearlier. Since there is no
meaningul concept of area for an undefined two-dimensional figure, the followingversion
of the program declares area( ) as abstract inside Figure. This,of course, means that all classes
derived from Figure must override area().
// Using
abstract
abstract methods and
class Figure
classes. I
PART
double diml;
double dim2;
class AbstractAreas {
public static void main (String args { ))
1/Figure f = new Figure (10, 10) ; // illegal now
Rectangle r = new Rectangle (9,, 5);
Triangle t = new Triangle (10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println ("Area is "+ £igref.area () );
Part I: The Java
180 Language
figref - t;
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!");
Sometimes you will want to prevent a class from being inherited. To do this, precede the
Declaring a class as final implicitly declares all of its methods
class declaration with final.
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 arnd relies upon its subclasses to provide PARTI
complete implementations.
Here is an example of a final class:
final class A {
Object defines the following methods, which means that they are available in every object.
Method Purpose
Object clone( ) Creates a new object that is the same as the object being cloned.
int hashCode( ) Returns the hash code associated with the invoking object.
void notifyAll( ) Resumes execution of all threads waiting on the invoking object.
The methods getClass(),notify( ), notifyAll( ), and wait() are declared as final. You
may override theothers.These methods are described elsewhere in this book. However,
notice two methods now: equals( ) and toString(). The equals( ) method compares the
contentsof two objects. It returns true if the objects are equivalent, and false otherwise.
P 1ojet04 me
sMO[e os Butoi 'poyjets pteeo sssehueupatlusn
4ndjno s1lqo ue uym pe Aegerane poyu os[V pfle s! sp 44Prao
4Dlqo jO uontusetesuetete Sunse suunja poupu ()8uungo, 'paeduoD
Sujg ssatqo yo dí) g uo Suypudp Asea ue kenba jo uogtetep aspatd auL