We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 38
INHERITANCE
Key Skills and Concepts
Understand inheritance basics
Call superclass constructors
Use super to access superclass members
Create a multilevel class hierarchy
ted
Know when constructors are execu! a
Understand superclass references to subclass object
Override methods a
Use overridden methods to support polymorphism
Use abstract classes
Use final
@ Know the Object class
RHHRRRHRAA
heritance is one of the three foundational principles of object-oriented programming because ita:
assifications. Using inheritance, you can create a general class that dix
the creation of hierarchical cl
traits common to a set of related items. This class can then be inherited by other, more specific case
each adding those things that are unique to it,
In the language of Java, a class that is inherited is called a superclass. The class that does the inher
called a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of th ¥
and methods defined by the superclass and adds its own, unique elements.
INHERITANCE BASICS abe
Java supports inheritance by allowing one class to incor
porate anoth into i 7 js dont!
using the extends keyword. Thus, the subelass adds to (exterids) the sone oe
Let's bepn with ashor example that lusts several ofthe key featutes of inheritance. The flo™
Program co a superclass caeg swreDShape, which stores the width and height of a two-dimen?
object, and a subclass called Triangle. Notice how the keyword extends is used-to oreate a subCHS
cre:
[-// & simple class hierarchy.
3) Ww
// A class for two-dimensional “bjecre,!
class TwoDshape'{ a i
double width;
4 (st iInheritance 235
double height;
void showDim() {
system.out:printin(*width and height are " +
width + " and " + height);
}
} ale A
// A subclass of TwoDShape for triangles. A ee) bo
class Triangle extends)'TwoDShape { ydnad , V= ate 9 b
String style; . ch “
‘Triangle inherits ‘TwoDShape.
double area() { 1
yeturn width * height / 2; ~— Triangle can refer to the members of
} ‘TwoDShape as if they were part of Triangle.
void showStyle() { os
system. out .printIn("Triangle is " + style);
}
}
class Shapes {
public static void main(String[] args) {
Triangle tl = new Triangle();
Triangle t2 = new Triangle();
ti.width = 4.0; <————— all members of Triangle are available to
t1.height ‘Triangle objects, even those inherited from
ti.style ‘TwoDShape.
t2.width = 8.0;
t2.height = 12.0;
t2.style = "outlined";
System.out .println("Info for t1 "); :
t1.showStyle(); ease
t1.showDim(); ~~ i
System.out. peintin ("area ig,"
a eliazea0) 7, be
Terence
a boronrcennbayany:
System.out.print1n("Info for t2: ");
t2.showStyle ();
t2.showDim() ; ter
System.out .print1n ("Ar 2 is "+ t2,area());
} i whe
}
output from this program is shown here:
Info for t1:236 > : Java Fundamentals
Triangle is filled
Width and height are 4.0 a!
Area is 8.0
nd 4.0
Info for t2:
Triangle is outlined
Width and height are 8.0 and 12.0
Area is 48.0 ~
Here, TwoDShape defines the attributes of a “generic” two-dimensional shape, such as
ype of TWoDShape, in this case, g
Brian
The Triangle class creates a specific typ
“Hips all of TwoDShape and adds the field style, the method area ), ang yy Ben,
re
.d in style. This can be any string that describes the rt,
oo ian,
Ws
angle, or triangle,
Triangle class in
showStyle( ). The triangle’s style is store
such as “filled”, “outlined”, “transparent”, or even
something like “warning symbol”, “isosceles”, [war
or “rounded”, The area( ) method computes and [|_|
returns the area of the triangle, and showStyle( )_ TwoPShape height
displays the triangle style, showDim(
Because Triangle includes all of the mem-
erclass, TwoDShape, it can access style ‘Tange
width and height ‘inside area( ). Also,” inside
main( ), objects t1 and ¢2 can refer to width and
height directly, as if they were part of Triangle. showStyle()
Figure 7-1 i
ig depicts concepvally how TwoDShape pig. 7.1 A conceptual depiction ofthe Thane
is incorporated into Triangle.
Even though TwoDShape is a superclass for Tri iti i
though Tv Jas tangle, it is also a completely independent,
class. Being a superclass for a subclass ddes not mean’ that the superclass cannot be eae ers
sed by itself. Fy
example, the following is perfectly valid.
area )
TwoDShape shape - new TwoDShape();
shape.width = 10;
shape.height = 20;
shape. showDim() ;
OF course, an object of TwoDShape has no kn
€
The general form of a class declaration that inher; go
E coess to any subclasses of TwoDShape.
rits a supercl
class subclass-name extends s1
uperclass-nam
// body of class a
‘A major advantage of inheritance is that once you h;
common to a set of objects, it can be used to create any uve. created a
can precisely tailor its own classification. For example, h imber of mo)
i re specific subclasses. Each uP” |
sulates rectangles. another subclass of TwoDShape that |Inheritance
237
a subclass of TwoDShape for rectangles.
Wy
tends TwobShape. {
class Rectangle ex
poolean isSquare() {
jf(width == height) return true;
return false;
)
double area() {
return width * height;
}
}
‘The Rectangle class includes TwoDShape and adds the methods isSquare( ). which determines if the
rectangle is square, and area( ), which computes the area of a rectangle. Notice that Rectangle does not
havea style ficld or a showStyle( ) method. Although Triangle adds those members, it does not mean that
Rectangle (or any other subclass of TwoDShape) must also add them. Except for sharing a common super-
Glass. each subclass is independent, Of course, subclasses can provide similar members, as is the case with
thearea( ) method. Although itis implemented differently, both Triangle and Rectangle provide this method
[gE] MEMBER ACCESS AND INHERITANCE _
wn an instance variable of a class will be declared private to prevent its
hheriting a class does not overrule the private access restriction. Thus,
Luperclass, it cannot access those members of the
if, as Shown here, width and height are made
‘As you leamed in Chapter 6, ofte
unauthorized use or tampering. In
even though a subclass includes all of the members of its s
superclass that have been declared private. For example,
private in TwoDShape, then Triangle will not be able to access them.
// private members of a superclass are not accessible by a subclass.
// This example will not compile.
// K class for two-dimensional objects~
class TwoDShape { Waterers
private double width; // these are) oj.
private double height; // now private
void showDim() {
System.out .printin("Width and height are “+
width +’" and)" + height);
} ap
We
} po a!
// x subclass of TwoDShape for triangles.— ?
class Triangle extends TwoDShape {
Cannot access a private member
String style;
{ of asipercliss. >
double area()
return width * height / 2; // Error! can't access ‘ocle
}238 Java Fundamentals
showStyle() {
id
System.out.printIn("Triangle is "+ style);
The Triangle class will not compile because the reference to width and height inside the areal ) mer,
causes an access violation. Since width and height are now declared private in TwoDShape, they
accessible only by other members of TwoDShape. Subclasses have no access to them.
Remember that class member that has been declared private will remain private to its class. is,
accessible by any code outside its class, including subclasses.
“At first. you might think that the fact that subclasses do not have access to the private members of supe.
classes is a serious restriction that would prevent Mie Use of private members in many situations, Hower,
this is not true. As explained in Chapter 6, Java programmers typically use cor methods to provizs
access to the private instance variables of a class. Here is a rewrite of the TwoDShape and Triangle clase,
that uses methods to access the private instance variables width and height.
these are
// now private
width and height.
ith ( return width; }
eight () { return height; } <——— Accessor method for width and bgt
(double w) { width = w; }
eight Geuiat h) { height = h; }
owbim() {
etem.out.printin("#idth and height are " +
| width + " and " + height);
88 of TwoDShape for triangles.
ngle extends TwoDShape {
ng style;
Use accessor methods provided by superclass.
double areal) { |
veturn getWidth() * getHeight() / 2;
}
System.out printin ("Triangle is "+ style);
}
i
class Shapee2 {
public static void main(String{) arge) {
Triangle t1 = new Triangle (
Triangle t2 = new Triangle();
|
|
|
| void shoustyle() {| —
Inheritance oa
setWidth (4 20);
getHeight (4.0);
style = "filled";
tl.
tl.
tle
setWidth (8.0);
12.
tz.setHeight (12.0);
tastyle = "outlined"
gystem.out-printIn ("Info for ti: ");
ti.showstyle () 7
t1.showDim() ;
gystem.out.printin("Area is " + t1.area());
system.out print1n();
system.out.printin("Info for t2: ");
t2.showStyle ();
t2.showDim() ;
system.out .println("Area is " + t2.area());
Q When should I make an instance variable private?
Ae are no hard and fast rules that fit every situation, but here are two general principles. If an
instance variable is to be used only by methods defined within its class, then it should be made
private. Ifan instance variable must be within certain bounds, then it should be private and made avail-
able only through accessor methods, This way, you can prevent invalid values from being assigned.
Furthermore, using accessor methods to access data lets you more easily change your class’s imple-
mentation without affecting the users of your class.. :
1 5 ‘| ul
phen creating a subclass, what keyword is used t0 include a superclass?
5 Does a subclass include the members of its superclass?
- Does a subclass have access to the private members of its superclass?
~——
Answers:ee ee
Java Fundamentals
E
CONSTRUCTORS AND INHERITANC
Ina hierarchy, itis
ible for both superclasses and subclasses to have their own construc
a possible for both supe
an important questi
‘or building an object of the subclass...
jon: what constructor is responsible for ee 4 oovetor for ian — a
Superclass, the one in the subclass, or both? The answer is, ce peconstuctor fort fs eae oon
the superclass portion of the object, and the constructor for aa fotany clement ey Part, :
makes sense because the superclass has no knowledge of se Se peer caibalss 1g)
» their construction must be sepatate. The preceding examples hav actice, most classes will pee &
ated automatically by Java, so this was not an Sees: Howe bo elert a AVE ean
Constructors. Here you will see how to handle this situation. a
When on oe efines ‘a constructor, the process is sealeiorvant oe, const
class object. The superclass Portion of the object is constructed automatically using its defaul
Uct the yy
It constrye
For example, here isa reworked version of Triangle that defines a constructor. It also makes Style privy
Since it is now set by the constructor. ea
/7 dd a constructor to Triangle.
/1 B® class for two-
dimensional objects.
class TwoDshape {
private double width; // these are
Private double height; // now private
k
// Recessor methods for width and height. |
double getWidEh() { return widt! }
double getHeight() { return height; }
void setwidth (doub1
ew) (width = wi;
void setHeight (double h) { height = h; }
void showDim() { ac
System. out .printin (‘Width and height aye! ® +
Midth 4 Wand * + height) }
} i
}
// B subclass of Twopsh:
class Triangle extends
private String style;
ape for triangles:
TwoDShape {
// Constructor
Triangle(String s, double w,
setWidth (w) ; < __ ntialize TwoDShape jos
Pe portion of o
setHeight (h) ; rednecks
style = 5;
}
le area() { 7
so petiesiacemiden (1 Gatualone (y 12;
} =a]
Inheritance 241
yoid showStyle() {
system.out .println("Triangle is " + style);
) ;
}
class Shapes3 {
public static void main(string[] args) {
Triangle tl = new Triangle("filled", 4.0, 4.0);
Triangle t2 = new Triangle("outlined", 8.0, 12.0);
system.out.println("Info for tl: ");
t1.showStyle() ;
ti.showDim() ;
system.out .printin("Area is " + t1.area());
system.out.printIn();
system.out .print1n ("
t2.showStyle();
t2.showDim() ;
system.out .printin("Area is " + t2.area());
}
}
Here, Triangle’s constructor initializes the members of TwoDClass that it inherits along with its own style
feline peeegeee
"When both the superclass and the subclass define constructors, the process is a bit more complicated
because both the superclass and subclass constructors must be executed. In this case you must use another
of Java’s keywords( super, which has two general forms. The first calls a supe: ynstructor. The second
is used to access a member of the supérclass that has been hidden.by a member of: class. Here, we will
look at its first use.
nfo for t2: ");
7A USING super TO CALL SUPERCLASS CONSTRUCTORS
A subclass can call a constructor defined by its superclass by use of the following form of super:,
super(parameter-list);
Here, parameter-list specifies any parameters needed by the constructor in the superclass. super( ) must
always be the first statement executed inside a subclass constructor. To see how super( ) is used, consider
the version of TwoDShape in the following program. It defines constrictor tha
height.
// Bad constructors to TwoDShape.
class Twopshape {
private double width; »
Private double height;
// Parameterized constructor...
TwoDShape (double w, double h) {<————A constructor for TwoDShape
width = w; "
height = h;242 Java Fundamentals
}
// Accessor methods for width and height.
double getWidth() { return width; }
double getHeight() { return height; }
void setWidth(double w) { width = w; }
void setHeight (double h) { height = h; }
void showDim() {
System.out.print1n("Width and height are " +
width +" and " + height);
// & subclass of TwoDShape for, triangles. -
class Triangle extends TwoDshape {
private String style; ~ -*
Triangle(String s, double w, double h) {
super(w, h); // call superclass constructor
style
} Use super( ) to execute the:
‘TwoDShape constructor.
‘webShape constr
double area() { . .
return getWidth(),*, getHeight() /.2;
} : rf
»void showStyle() {
System.out.printin("Triangle is " + style);
}
}
class Shapes4 {
public static void main(String{] args) {
Triangle t1 = new Triangle("filled", 4.0, 4.0);
Triangle t2,= new Triangle ("outlined", 8,0, 12.0)+
System.out.printin("Info for ti: ");
t1.showStyle () ;
t1.showDim() ;
System.out.println("Area is " + tl.area());
System.out.printin();
System.out.printIn("Info for t2: ");
t2.showStyle();
t2.showDim() ;
System.out .printIn("Area is." + t2.area());Inheritance 243
iangle( calls super() with the parameters w and h. This causes the TwoDShape( ) constructor to be
hich initializes width and height using these values. Triangle no longer initializes these values itself.
tpneed only initialize the value unique to it: style. This leaves TwoDShape free to construct its portion in any
wisper that it so chooses. Furthermore, TwoDShape can add funetionality about which existing subclasses
fave no knowledge thus preventing existing code from breaking.
i siy form of constructor defined by the superclass can be called by super ), The constructor executed
1 be the one that matches the arguments. For example, here are expanded versions of both TwoDShape
tnd Triangle that include default constructors and constructors that take one argument. =
plore, T
called, Wh
J) Rad more constructors to TwoDShape.
class TwoDShape {
private double width;
private double height;
// & default constructor,
TwoDshape() {
width = height = 0.0;
}
// Parameterized constructor.
TwoDShape (double w, double h) {
width = w;
height = h;
) is
// construct object with equal width and height.
‘TwoDShape (double x) »{ a ibentijuc®) sip
width = height
}
// Recessor methods for (width and height.
double getWidth() { return width; }
double getHeight() { return height; }
void setWidth(double w) .{ width = w; }
void setHeight (double h) { height = h; }
void showDim() {
System.out .printIn("Width and height are " +
width + " and " + height);
/I ®& subclass of TwoDShape for triangles.
Class Triangle extends TwoDShape {
private String style;
// & default constructor.
Triangle () {wa
super ();