gpt4 book ai didi

java - 初学者的继承

转载 作者:搜寻专家 更新时间:2023-10-31 19:40:02 26 4
gpt4 key购买 nike

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

public static void main(String[] args)

So类继承:

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

但是,当我尝试在主类中使用 BoxWeight 时,在使用过程中出现错误

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

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

最佳答案

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

BoxWeight 不需要在 Inheritance 类中。

相反,从 Inheritance 类中删除 BoxWeight

并将Inheritance.BoxWeight更改为BoxWeight

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

Inheritance.BoxWeight mybox1 = new Inheritance().new BoxWeight(...);

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

关于java - 初学者的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15010901/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com