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


BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
}
}
该程序的输出显示如下:
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3
Volume of mybox2 is 24.0
Weight of mybox2 is 0.076
BoxWeight 继承了Box 的所有特征并为自己增添了一个weight 成员 。没有必要让BoxWeight 重新创建Box 中的所有特征 。为满足需要我们只要扩展Box就可以了 。
继承的一个主要优势在于一旦你已经创建了一个超类,而该超类定义了适用于一组对象的属性,它可用来创建任何数量的说明更多细节的子类 。每一个子类能够正好制作它自己的分类 。例如,下面的类继承了Box并增加了一个颜色属性:
// Here, Box is extended to include color.
class ColorBox extends Box {
int color; // color of box
ColorBox(double w, double h, double d, int c) {
width = w;
height = h;
depth = d;
color = c;
}
}
记?。?一旦你已经创建了一个定义了对象一般属性的超类 , 该超类可以被继承以生成特殊用途的类 。每一个子类只增添它自己独特的属性 。这是继承的本质 。
超类变量可以引用子类对象
超类的一个引用变量可以被任何从该超类派生的子类的引用赋值 。你将发现继承的这个方面在很多条件下是很有用的 。例如,考虑下面的程序:
class RefDemo {
public static void main(String args[]) {
BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
Box plainbox = new Box(); double vol;
vol = weightbox.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " + weightbox.weight);
System.out.println();
// assign BoxWeight reference to Box reference
plainbox = weightbox;
vol = plainbox.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox does not define a weight member. */
// System.out.println("Weight of plainbox is " + plainbox.weight);
}
}
这里,weightbox 是BoxWeight 对象的一个引用 , plainbox 是Box对象的一个引用 。既然BoxWeight 是Box的一个子类,允许用一个weightbox 对象的引用给plainbox 赋值 。
当一个子类对象的引用被赋给一个超类引用变量时,你只能访问超类定义的对象的那一部分 。这是为什么plainbox 不能访问weight 的原因,甚至是它引用了一个BoxWeight 对象也不行 。仔细想一想,这是有道理的,因为超类不知道子类增加的属性 。这就是本程序中的最后一行被注释掉的原因 。Box的引用访问weight 域是不可能的,因为它没有定义 。
用Java继承和多态实现编写代码代码如下:
abstract class DongWu {
public abstract void info();
}
class Bird extends DongWu {
@Override
public void info() {
System.out.println("我是一只鸟 。");
}
}
class Fish extends DongWu {
@Override
public void info() {
System.out.println("我是一条鱼 。");
}
}
public class App5 {
public static void main(String[] args) {
DongWu bird = new Bird();
bird.info();
DongWu fish = new Fish();
fish.info();
}
}
如何在Java中使用子类继承父类的父类,举个例子看看 , 谢谢class Animal{//动物类

推荐阅读