【问题标题】:java object not compiledjava对象未编译
【发布时间】:2020-06-12 19:36:09
【问题描述】:

我有以下java代码段,

class Box{
    int length;
    int width;
    int height;

    Box(int length, int width, int height){
        this.length=length;
        this.width=width;
        this.height=height;
    }
    Box(){
        this.length=1;
        this.width=1;
        this.height=1;
    }
}
class Demo{
    public static void main(String args[]){
        Box b1=new Box(); //calling default
        System.out.println("Length : "+b1.length);
        System.out.println("Width  : "+b1.width);
        System.out.println("Height : "+b1.height);

        b1.Box(12,5,3);
        System.out.println();
    }
}

但是当我在代码高亮而不是编译之后编译 java 文件时 b1.Box(12,5,3);

问题是什么,如何解决?

【问题讨论】:

  • b1 = new Box(12,5,3);?
  • 构造函数不是方法。
  • b1.length=12;b1.width=5;b1.height=3;
  • 为什么不首先“直接”调用参数化构造函数呢?为什么还要使用默认构造函数?

标签: java oop


【解决方案1】:

Box(12,5,3) 是参数化构造函数,而不是Box 类的方法,因此无需使用引用调用它。不使用对象直接调用即可。

因此,您可以使用参数化的构造函数,而不是使用默认构造函数声明b1

Box b1 = new Box(12, 5, 3);

或者你可以在Box类中创建一个setter函数,如果你需要稍后将值设置为

public void setDimensions(int length, int width, int height) {
    this.length = length;
    this.width = width;
    this.height = height;
}

然后b1.Box(12,5,3); 变为b1.setDimensions(12,5,3);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    相关资源
    最近更新 更多