java中继承代码实例 java中的继承如何实现( 二 )


superOb.showij();
System.out.println();
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();
}
}
该程序的输出如下:
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
像你所看到的,子类B包括它的超类A中的所有成员 。这是为什么subOb 可以获取i和j 以及调用showij( ) 方法的原因 。同样 , sum( ) 内部,i和j可以被直接引用,就像它们是B的一部分 。
尽管A是B的超类,它也是一个完全独立的类 。作为一个子类的超类并不意味着超类不能被自己使用 。而且,一个子类可以是另一个类的超类 。声明一个继承超类的类的通常形式如下:
class subclass-name extends superclass-name {
// body of class
}
你只能给你所创建的每个子类定义一个超类 。Java 不支持多超类的继承(这与C++ 不同,在C++中,你可以继承多个基础类) 。你可以按照规定创建一个继承的层次 。该层次中,一个子类成为另一个子类的超类 。然而,没有类可以成为它自己的超类 。
成员的访问和继承
尽管子类包括超类的所有成员,它不能访问超类中被声明成private 的成员 。例如 , 考虑下面简单的类层次结构:
/* 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;
private int j; // private to A
void setij(int x, int y) {
i = x; j = y;
}
}
// 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);
}
}
该程序不会编译 , 因为B中sum( ) 方法内部对j的引用是不合法的 。既然j被声明成private,它只能被它自己类中的其他成员访问 。子类没权访问它 。
注意:一个被定义成private 的类成员为此类私有 , 它不能被该类外的所有代码访问,包括子类 。
更实际的例子
让我们看一个更实际的例子,该例子有助于阐述继承的作用 。新的类将包含一个盒子的宽度、高度、深度 。
// This program uses inheritance to extend Box.
class Box {
double width; double height; double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume double
volume() {
return width * height * depth;
}
}
BoxWeight extends Box {
double weight; // weight of box
// constructor for BoxWeight
BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d;
weight = m;
}
}
class DemoBoxWeight {
public static void main(String args[]) {

推荐阅读