CLASSES
Examples of Inheritance
8.2.1
public class Point {
public int x, y;
protected int useCount = 0;
static protected int totalUseCount = 0;
public void move(int dx, int dy) {
x += dx; y += dy; useCount++; totalUseCount++;
}
}
the
public
and
protected
fields
x
,
y
,
useCount
and
totalUseCount
are inher
ited in all subclasses of
Point
. Therefore, this test program, in another package,
can be compiled successfully:
class Test extends points.Point {
public void moveBack(int dx, int dy) {
x = dx; y = dy; useCount++; totalUseCount++;
}
}
8.2.1.3
Inheritance with
private
In the example:
class Point {
int x, y;
void move(int dx, int dy) {
x += dx; y += dy; totalMoves++;
}
private static int totalMoves;
void printMoves() { System.out.println(totalMoves); }
}
class Point3d extends Point {
int z;
void move(int dx, int dy, int dz) {
super.move(dx, dy); z += dz; totalMoves++;
}
}
the class variable
totalMoves
can be used only within the class
Point
; it is not
inherited by the subclass
Point3d
. A compile time error occurs at the point where
method
move
of class
Point3d
tries to increment
totalMoves
.
141
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved