JAVA课程和对象....我班上会有什么

时间:2014-10-09 14:19:33

标签: java class methods

对于“这一行”,代码将如何? 我知道对于“第二部分”setName,setWidth,setHeight ....将是Box类中的方法...但我坚持“这一行”......它会是1方法吗?

    Box box1 = new Box(string, double , double); //this line

    //2nd part
    Box box2 = new Box(); //i get this part
    Box2.setName(String);
    box2.setWidth(double);
    box2.setHeight(double);

3 个答案:

答案 0 :(得分:1)

您是否已创建构造函数并在类Box中声明变量?

public class Box {

    private double height;
    private double width;
    private String name;

    // constructor for setting those variables
    public Box(double height, double width, String name) {

        this.height = height;
        this.width = width;
        this.name = name;
    }

    // constructor for creating object without setting variables
    public Box() {}
}

然后你可以创建一个像这样的对象:

Box box1 = new Box(20, 10.5, "MyName");
Box box2 = new Box();

答案 1 :(得分:0)

Box1是使用构造函数创建的,您传入的参数用于创建Box对象的Name,Width和Height字段。

使用Box2,您将使用默认构造函数Box box2 = new Box();创建对象,然后设置该对象的字段。

答案 2 :(得分:0)

您需要有一个构造函数来传递参数。我只做了自定义构造函数,要创建Box2对象,还需要一个空白构造函数。

public class Box {
    public Box(String string, Double double1, Double double2) {
        //Set your variables
    }
    public Box() {
        //This is the standard constructor you use for Box2
    }

    //Specify your methods like setName(String s) etc.
}
相关问题