0% found this document useful (0 votes)
7 views

Java Module-3 Part -A(Inheritance )Book Notes

Uploaded by

SAMANVITA Rd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java Module-3 Part -A(Inheritance )Book Notes

Uploaded by

SAMANVITA Rd
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

CHAPTER

Inheritance

Tnheritanceis one of the cormerstonesof object-oriented programming because it allows


the creation of hierarchical classifications. Using inheritance, you can create a general
Lclass that definesetraits common to a set of related items. This class can then be inherited
byother, more specific classes, each adding those things that are unique to it. Inthe terminology
Java, a class thatis inherited is calleda superclass. The class that does the inheriting is called
of
a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of the
instance variables and methods definedby the superclass and adds its own, unique elements.

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/A simple example of inheritance.

1/Create a superclass.
class A

int i, ji

void showij () {
System.out.println ("i and j: "+ i + " n + i):

//Create a subclass by extending class A.


class B extends A {
int k;

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()}

// The superclass may be used by itself.


superob.i = 10;
superob.j = 20;
System. out.println ("Contents of superOb: ");
superob.showij):
System. out .println():

/* The subclass has access to all public members of


its superclass. */
subob.i = 7;
subOb,j = 8;
subob,k = 9;
System,out.println ("Contents of subOb: ");
subOb. showij();
subob.showk ()
System. out.println():

System. out.println("Sum of i, j and k in subOb: ");


subob. sum () ;

The output from this program is shown here:

Contents of superOb:
i and j: 10 20

Contents of subob:
i and j: 7 8
k: 9

Sum of i, j and k in subOb:


i+j+k: 24
As you can see, the subclass B includes all of the members of its superclass, A. This is

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:

class subclass-name extends superclass-name {

//body of class
Chapter 8: Inheritance 159

You can only specify one


superclass for any subclass that you create. Java
support the inheritance of does not
multiple superclasses into a single subclass. You
create a hierarchy of inheritance can,as stated,
in which a subclass
However, no class can be a becomes a superclass of another subclass.

I
superclass of itself.

Member Access and Inheritance


PART

Although a subclass includes all of the


members of its superclass, it cannot access those
members of the superclass that have been declared
as private. For example, consider the
followingsimple class hierarchy:

/* In a class hierarchy, private


members remain
private to their class.

This program contains an error and will


not
compile,

Create a superclass.
/
class A{
int i; //public by default
private int j // private to A

void setij (int x, int y) {


i = X;

1/A's j is not accessible here.


class B extends A {
int total;
void sum () {
total = i + j; / ERROR, j is not accessible here

class Access {
public static void main (String args (] )
{
B subOb = new B();

subOb. setij (10, 12) :

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

( the keyword super.


super has two general forms. The first calls the superclass' constructor. The
second is
used to access a member of the superclass that has been hidden by a member of a
subclass.
Each use is examined here.

Using superto Call Superclass Constructors


A subclass can calla 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 statementexecuted inside a subclass' constructor.
To see how super() is used,consider this improved version of the BoxWeight() class:

// BoxWeight now uses super to initialize its Box attributes.


class BoxWeight extends { Bx
double weight; //weight of box

1/ initialize width, height, and depth using super ()


BoxWeight (double w, double h, double d, double m) {
super (w, h, d); // call superclass constructor
weight = m;

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

1/ Create a subclass by extending class A.


class B extends A{
int i; / this i hide8 the i in A

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 (]) {

B subOb = new B(1, 2):

subob, show ()

This program displays the following:

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.

Creating a Muitilevel Hierarchy


Up to this point, we have been using simple class hierarchies that consist of only a superclass
and a subclass. However, you can build hierarchies that contain as many layers of inheritance
as you like. As mentioned,it is perfectly acceptable to use a subclass as a superclass of another.

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

shipping such a parcel.

1/Bxtend BoxWeight to include shipping costs.

// Start with Box.


class Box
private double width;
private double height;
private double depth;
168 Part I: The Java
Language

1/construct clone of an object


Box (BOx ob) pass object to
width = constructor
ob.width;
height = ob.height:
depth = ob.depth;

//constructor used when all


Box (double w, dimensions specified
double h, double d) {
width = Wi
height = h;
depth = d;

7/ constructor used when no


dimensions specified
Box () {
width = -1; // use -1 to indicate
height = -1; / an uninitialized

depth = -1; // box

1/constructor used when cube is created


Box (double len) {
width = height = depth = len;

//compute and return volume


double volume() {
return width * height * depth;

// Add weight.
class BoxWeight extends Box
{
double weight; // weight of£ box

|/ construct clone of an object


BoxWeight (BoxWeight ob) { // pass object to constructor
super (ob);
weight = ob.weight;

17 constructor when all parameters are specified


BoxWeight (double w, double h, double d, double m){
super(w, h, d); //call superclass constructor
weight = m;

1/ default constructor
BoxWeight () {
Super(0;
weight = -1;
Chapter 8: In heritance 169

1/ constructor used when cube is created


BoxWeight (double len, double m) (
super (len);
we ight = m;

PARTI

//Add shipping costs.


class Shipment extends BoxWeight

{
double cost;

/ construct clone of an object

Shipment (Shipment ob) { //pass object to constructor


super (ob);
Cost = ob.cost;

1/ constructor when all parameters are specified


Shipment (double w, double h, double d,
double m, double c)
super (W, h, d, m); // call superclass constructor
COst = C;

// default constructor
Shipment () {
super );
cost = -l;

1/ constructor used when cube is created


Shipment (double len, double m, double c) {

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

The output of this program is shownhere:


Volume of shipment1 is 3000.0
Weight of shipment is 10.0 1

Shipping cost: $3.41

Volume of shipment2 is 24.0


Weight of shipment 2 is 0.76
Shipping cost: $1.28
Because of inheritance, Shipment can make use of the previously defined classes of Box
and BoxWeight, adding only the extra informationit needs for its own,specific application.
Thìs is part of the value of inheritance; it allows the reuse of code.
This example illustrates one other important point: super() always refers to the constructor
in the closest superclass. The super() in Shipment calls the constructor in BoxWeight. The
super( ) in BoxWeight calls the constructor in Box. In a class hierarchy, if a superclass

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.

NoTE program,the entire class hierarchy, including Box, BoxWeight, and


In the preceding

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

files is the norn, not the exception, in creating class hierarchies.

VWhen Constructors Are Called


in what order are the constructors for the classes that make up
When a class hierarchy is created,

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

//Demonstrate when constructors are called.

1/Create a super class.


class A{
A() {
");
System, out.println(" Inside A's constructor.
Inheritance 171
Chapter 8:

//Create a subclass by extending class A.

class B extends A

{
B) {
constructor. ");
System. out.println ("Ingide B's
PARTI

/7 Create another subclass by extending B.

class C extends B
C)
{
");
System.out.println ("Inside C's constructor.

class CallingCons
public static void main(String args []){
Cc = new C();

The output from this program is shown here:

Inside A's constructor


Inside B's constructor
Inside C's constructor

in order of derivation.
As you can see, the constructors are called

you think about makes sense


it, it that constructors are executed in order of derivation.
If

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.

Therefore, it must be executed first.

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

by the superclass will be hidden.Consider the following:

//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{

B(int a, int b, int


c) (
super (a, b)i

// display k - this
void show (){ overrides show () in A

System.out.println ("k: + k); "

class Override {
public static void main (String
B subOb = new B(1, 2, args [)){
3) ;

subob.show (); //this ca1ls show() in B

The output produced by this program is shownhere:


k: 3
When show( ) is invoked on an object of type B, the version of show( defined within )
B
used. That is, the version of show() inside B overrides
is
the version declared in A.
If you wish to access the superclass version of an overriddenmethod, you can do so by
using super.For example, in this version of B, the superclass version of show( ) is invoked
within the subclass' version. This allows all instance variables to be
displayed.

class B extends A {

int k;

B (int a, int b, int c) {


Super (a,b) ;
k = C;
void show () {
super.show(); // this calls A's show()
System.out .print ln("k: " + k) ;

Ifyou substitute this version of A into the previousprogram, you will see the following
output:

i and j: 1 2
k: 3

Here, super.show() calls the superclass version of show().


174 Part I: The Java Language

Dynamic Method Dispatch


While the 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 atrun time, rather than compile time.
Dynamic method dispatch is important because this is how Java implements run-time
polymorphism.
Let's begin by restating an importantprinciple: a superclass reference variable can refer
to a subclass object. Java uses this fact to resolve calls to overridden methods at run time. Here

is how. When anoverridden method througha superclass reference, Java determines


called

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)

that determines which version of an overridden method will be executed.Therefore, if a


superclass contains a method that is overriddenby a subclass, then when different types
of objects are referred to through a superclass reference variable, different versions of the
method are executed. class
Here an example that illustrates dynamic method dispatch:
is
-sypes
I/Dynamic Method Dispatch
class A |A
void callme () {
System.out .println ("Inside A'S callme method") ;

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 [] ) (

A a = new A(); // object of type A


Bb=
new B() ; 1/ object of type B
Cc
= new c(); // object of type C
A r; // obtain a reference of type A
Chapter 8: Inheritance 175

r = a; //r refers to an object A

r.callme (); |callg A's version of callme


r = b; //r refers to a B object
r.callme (); / calls B's version of callme

r= c; // r refers to a c object
r.callme(); // calls C's version of£ callme

The output from the program is shown here:

Inside A's callme method


Inside B's callme method
Inside C's callme method

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.

Why Overridden Methods?


As stated earlier, overridden methods allow polymorphism.
Java to support run-time
Polymorphism is essential to object-oriented programming for one reason: it allows a
general class to specify methods that will be common to all of its derivatives,while allowing
subclasses to define the specific implementation of some or all of those mnethods.Overridden
methodsare another way that Java implements the "oneinterface, multiple methods"aspect
of polymorphism.
Part of the key to successfully applying polymorphism is understanding that the
superclasses and subclasses form a moves from lesser to greater specialization.
hierarchy which
Used correctly, the superclass provides all elements that a subclass can use directly. It also
defines those methods that the derived class must implementon its own. This allows the
subclass the flexibility to define its own methods,yet still enforces a consistent interface.
Thus, by combining inheritance with overridden methods, a superclass can define the general
formofthe methods that will be used by all of its subclasses.
Dynamic,run-time polymorphism is one of the most powerful mechanismsthat object
oriented design brings to bear on code reuse and robustness. The ability of existing code
libraries to cal methods on instances of new classes without recompiling while maintaining
a clean abstract interface is a profoundly powerful tool.
176 Part I: The Java Language

Applying Method Overriding


Let's look at a more practical example
that uses method overriding. The following program
creates a superclass Figure that stores the dimensions of a
called
also defines a method called
two-dimensional object. It
area() that computesthe area of an object. The
program derives
two subclasses from Figure. The first is Rectangleand the second is
Triangle. Each of
these subclasses overrides area( )
so that it returns the area of a rectangle
and a triangle,
respectively.

1/ Using run-time
polymorphism.
class Figure
double diml;
double dim2;

Figure (double a, double b) {


diml a:
dim2 = b;

double area(){
System. out.println ("Area for Figure is undefined. ");
return 0;

class Rectangle extends Figure {


Rectangle (double a, double b) {
super (a, b);

1/override area for rectangle


double area()
System. out.println ("Inside Area for Rectangle. ") ;
return diml * dim2 :
}
class Triangle extends Figure {
Triangle (double a, double b) {
super (a, b);

11 override area for right triangle


double area() {
System.out.println ("Inside Area for Triangle. ") ;
return dim1 * dim2/ 2;

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 ());

The output from the program is shownhere:

Inside Area for Rectangle.


Area is 45
Inside Area for Triangle.
Area is 40
Area for Figure is undefined.
Area is 0

Through the dual mechanisms of inheritance and run-time polymorphism, it is possible

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.

Using Abstract Classes


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 createa superclass that only defines a generalizedform that

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

definition of area( ) simply a


is placeholder. It will not compute and display the area of any
type of object.
As you will see as you create your own class libraries, it is not uncommon for a method
to haveno meaningful definition in the context of its superclass. You can harndle this situation
two ways. One way, as shownin the previousexample, is to simply have it report a warning
mesage.While this approach can be useful in certain situations--such as debugging -it is
not usually appropriate.You may have methods that must be overridden by the subclass
in order for the subclass to have any meaning. Consider the class Triangle. It has no meaning
if area()is not defined. In this case, you want someway to ensure that a subclass does, indeed,

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:

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 keyword in front of the class keyword
abstract
at the beginning of the class declaration. 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 itself declared abstract.
Here is a simple example of a class with an abstract method, followed by a class which
implements that method:

1/ASimple demonstration of abstract.


abstract class A {
abstract void callme () ;

//concrete methods are still allowed in abstract classes


void callmetOo() {
System.out.println ("This is a concrete method, ")
;

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

object references, because Java's approach to run-time


polymorphism is implemented through
the use of superclass references. Thus, it must be possible to create a reference to an abstract
class so that it can be used to point to a subclass object. You willsee this feature put to use in
the next example.
Chapter 8: Inheritance 179

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;

Figure (double a, double b) {


diml = a;
dim2 = b;

1/area is now an abstract method


abstract double area() ;

class Rectangle extends Figure {


Rectangle (double a, double b) {
super (a, b);

//override area for rectangle


double area()
System. out.println ("Inside Area for Rectangle. ") i
return diml * dim2;

class Triangle extends Figure {


Triangle (double a, double b) {
super (a,b);

1/override area for right triangle


double area()
System.out .print ln("Inside Area for Triangle. );
return diml * dim2 / 2;

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;

System,out.println("Area is "+ figref. area())


As the comment
type Figure,since it is
inside )
main( indicates, it
is no longer
now abstract. And,all possible to declare
objects of
prove this to subclasses of Figure
must override
yourself, try creating a area(). To
a compile-time subclass that does not
error. override area( ).You will
receive
Although it is not
possible to create an
variable of type Figure. object of type
Figure, you can
Thevariable figref is create a reference
that it can be used to declared asa reference to
refer to an object Figure, which means
of any class derived
through superclass from Figure. As
reference variables that overridden explained, it is
methods are resolved at run
time.

Using final with Inheritance


The keyword final has three
uses. First, it can be used
to create the
constant. This use was describedin the equivalent of a named
to inheritance. Both are preceding chapter. The other two uses
examined here. of final apply

Using final to Prevent Overriding


While methodoverriding is one of Java's most
powerful
you will want to prevent it from features, there will be times when
occurring. To disallowamethod from being
specify final as a modifier at the overridden,
start of its declaration.
be overridden. Methods declared as final cannot
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!");

Because meth( )is declared as final, it


cannotbe overridden in B. If you attempt to do
so, a compile-time error will result.
Methods declared as final can
sometimes provide a performance
compiler is free to inline calls to them enhancement: The
because it "knows" they will not be
byasubclass. When asmall final method overridden
is called, often the Java
bytecode for the subroutine directly compiler can copy the
inline with the compiledcode of
the calling method,
thus eliminating the costly overhead
associated with a method call. Inlining is
option with final methods. only an
Normally,Java resolves calls to
time. Thís is called late methods dynamically, at run
binding. However, since final
toone can be resolved at compile time. This is methods cannot be overridden, a call
called early binding.
Chapter 8: Inheritance 181

Using final to Prevent Inheritance

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 {

1/The following class is illegal.


class B extends A { // ERROR! Can't subclass A

As the comments imply, it is illegal for B to inherit A since A is declared as final.

The Object Class


There is one special class, Object, defined by Java. All other classes are subclasses of Object.
That is, Object is a superclass of all other classes. This means that a reference variable of type
Object can refer to an object of any other class. Also,since arrays are implemented as classes,
a variable of type Object can also refer to any array.

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.

boolean equals(0bject objec) Determines whether one object is equal to another.

void finalize( ) Called before an unused object is recycled.

Class getClass( ) |Obtains the class of an object at run time.

int hashCode( ) Returns the hash code associated with the invoking object.

void notify( ) Resumes execution of a thread waiting on the invoking object.

void notifyAll( ) Resumes execution of all threads waiting on the invoking object.

|String toString( ) Returns a string that describes the object.

void wait( Waits on another thread of execution.


)
void wait(long milliseconds)

void wait(long milliseconds,


int nanoseconds)

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

You might also like