CLASSES
Examples of Inheritance
8.2.1
class Point {
int x, y;
private Point() { reset(); }
Point(int x, int y) { this.x = x; this.y = y; }
private void reset() { this.x = 0; this.y = 0; }
}
class ColoredPoint extends Point {
int color;
void clear() { reset(); }
//
error
}
class Test {
public static void main(String[] args) {
ColoredPoint c = new ColoredPoint(0, 0); //
error
c.reset();
//
error
}
}
causes four compile time errors:
An error occurs because
ColoredPoint
has no constructor declared with two
integer parameters, as requested by the use in
main
. This illustrates the fact
that
ColoredPoint
does not inherit the constructors of its superclass
Point
.
Another error occurs because
ColoredPoint
declares no constructors, and
therefore a default constructor for it is automatically created ( 8.6.7), and this
default constructor is equivalent to:
ColoredPoint() { super(); }
which invokes the constructor, with no arguments, for the direct superclass of
the class
ColoredPoint
. The error is that the constructor for
Point
that takes
no arguments is
private
, and therefore is not accessible outside the class
Point
, even through a superclass constructor invocation ( 8.6.5).
Two more errors occur because the method
reset
of class
Point
is
private
,
and therefore is not inherited by class
ColoredPoint
. The method invoca
tions in method
clear
of class
ColoredPoint
and in method
main
of class
Test
are therefore not correct.
8.2.1 Examples of Inheritance
This section illustrates inheritance of class members through several examples.
8.2.1.1
Example: Inheritance with Default Access
Consider the example where the
points
package declares two compilation units:
139
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