JAVA一个盒子(继承)

继承是面向对象编程技术的一块基石,因为它允许创建分等级层次的类。运用继承,能够创建一个通用类,定义一系列相关项目的一般特性。该类可以被更具体的类继承,每个具体的类都增加一些自己特有的东西。

 package JAVA_Project_01_05;

//继承一个类,只要用extends关键字把一个类的定义合并到另一个中便可。
// 语法格式:(public)class子类名extends父类名。在Java术语中,被继承的类叫超类或基类,
// 继承超类的类叫派生类或子类。
//
//· 尽管子类包括超类的所有成员,但它不能访问超类中被声明成private的成员。
//
//· 超类的一个引用变量可以被任何从该超类派生的子类的引用赋值,即超类变量可以引用子类对象。
// 当一个子类对象的引用被赋给一个超类引用变量时,只能访问超类定义的对象的一部分。
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;//用-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) {//Java程序主入口处

        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);

        //System.out.printf("盒子box的重量:%s%n",box.weight);

        Box box2 = new BoxWeight();//超类引用子类对象

    }

}

/*
(1)程序中定义一个超类及继承超类的子类。其中在超类中定义一个盒子的高度、宽度和深度,
子类继承超类的所有特片并为自己增添一个重量成员。继承可以让子类没有必要重新创建超类中的所有特征。

(2)在main()主方法中在子类带参数实例化对象时,由于继承超类,则需要打印超类
默认构造方法中的语句IamaBox。当超类不带参数实例化对象时调用默认构造方法也打印出Iam aBox。
将子类对象赋给超类变量,weight是子类的一个属性,超类不知道子类增加的属性,
则超类不能获取子类属性weight的值。超类变量引用子类对象,可以看作是先实例化超类接着实例化子类对象,
则打印出超类和子类默认构造方法中的语句。
 */
发布了70 篇原创文章 · 获赞 10 · 访问量 3186

猜你喜欢

转载自blog.csdn.net/JN_Cat/article/details/103994877