继承是面向对象编程技术的一块基石,因为它允许创建分等级层次的类。运用继承,能够创建一个通用类,定义一系列相关项目的一般特性。该类可以被更具体的类继承,每个具体的类都增加一些自己特有的东西。
package JAVA_Project_01_05;
class Box {
double width;
double height;
double depth;
Box(Box box) {
this.width = box.width;
this.height = box.height;
this.depth = box.depth;
}
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Box() {
this.width = -1;
this.height = -1;
this.depth = -1;
System.out.println("IamaBox");
}
Box(double len) {
this.width = this.height = this.depth = len;
}
double volume() {
return width * height * depth;
}
}
class BoxWeight extends Box {
double weight;
BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d;
weight = m;
}
BoxWeight() {
System.out.println("IamasmallBox");
}
}
public class TextExtends {
public static void main(String[] args) {
BoxWeight weightBox = new BoxWeight(10, 20, 15, 34.0);
Box box = new Box();
double vol;
vol = weightBox.volume();
System.out.printf("盒子box1的体积:%s%n", vol);
System.out.printf("盒子box1的重量:%s%n", weightBox.weight);
box = weightBox;
vol = box.volume();
System.out.printf("盒子box的体积:%s%n", vol);
Box box2 = new BoxWeight();
}
}