8.2.1
Examples of Inheritance
CLASSES
package points;
public class Point {
int x, y;
public void move(int dx, int dy) { x += dx; y += dy; }
}
and:
package points;
public class Point3d extends Point {
int z;
public void move(int dx, int dy, int dz) {
x += dx; y += dy; z += dz;
}
}
and a third compilation unit, in another package, is:
import points.Point3d;
class Point4d extends Point3d {
int w;
public void move(int dx, int dy, int dz, int dw) {
x += dx; y += dy; z += dz; w += dw; //
compile time errors
}
}
Here both classes in the
points
 package compile. The class
Point3d
 inherits the
fields
x
 and
y
 of class
Point
, because it is in the same package as
Point
. The
class
Point4d
, which is in a different package, does not inherit the fields
x
 and
y
of class
Point
 or the field
z
 of class
Point3d
, and so fails to compile.
A better way to write the third compilation unit would be:
import points.Point3d;
class Point4d extends Point3d {
int w;
public void move(int dx, int dy, int dz, int dw) {
super.move(dx, dy, dz); w += dw;
}
}
using the
move
 method of the superclass
Point3d
 to process
dx
,
dy
, and
dz
. If
Point4d
 is written in this way it will compile without errors.
8.2.1.2
Inheritance with
public
and
protected
Given the class
Point
:
package points;
140






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

java hosting

 

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