继承初学者

gbk*_*gbk 5 java inheritance

我刚刚开始学习java,所以现在我读到了继承这种可能性,所以尝试创建必须创建对象框的类.并使用继承实现新属性来创建对象.我尝试将每个类放在单独的文件中,因此在创建类之后,尝试使用它

public static void main(String[] args)
Run Code Online (Sandbox Code Playgroud)

所以类继承:

 public class Inheritance {
double width;
double height;
double depth;
Inheritance (Inheritance object){
    width = object.width;
    height = object.height;
    depth = object.depth;
}
Inheritance ( double w, double h, double d){
    width = w;
    height = h;
    depth = d;
}
Inheritance (){
    width = -1;
    height = -1;
    depth = -1;
}
Inheritance (double len){
    width=height=depth=len;
}
double volumeBox (){
    return width*height*depth;
}
class BoxWeight extends Inheritance {
    double weight;
    BoxWeight (double w, double h, double d, double m){
        super(w,h,d);
        weight = m;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试在主类中使用BoxWeight时,在使用过程中我遇到了错误

public class MainModule {
    public static void main(String[] args) {
    Inheritance.BoxWeight mybox1 = new Inheritance.BoxWeight(9, 9, 9, 9);
....
Run Code Online (Sandbox Code Playgroud)

错误 - 无法访问类型为继承的封闭实例.哪里我错了?

Duk*_*ing 4

就目前情况而言,BoxWeight需要一个实例Inheritance才能工作(就像访问非静态变量或函数需要实例一样,访问非静态内部类也是如此)。如果您将其更改为static它会起作用,但这不是必需的。

BoxWeight不需要在Inheritance班级内部。

相反,将其BoxWeight移出班级Inheritance

并更改Inheritance.BoxWeightBoxWeight.

编辑:为了完整性,您也可以这样做:

Inheritance.BoxWeight mybox1 = new Inheritance().new BoxWeight(...);
Run Code Online (Sandbox Code Playgroud)

Inheritance.BoxWeight只是类型,所以上面的内容不适用。但要创建 的实例BoxWeight,您需要一个Inheritance使用 来创建的对象new Inheritance()