【问题标题】:JAVA classes and objects....what will be in my classJAVA 类和对象....我的课上会有什么
【发布时间】:2014-12-04 12:38:17
【问题描述】:

对于“这一行”的代码将如何? 我知道对于“第二部分”,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);

【问题讨论】:

  • 所以你知道box1是一个对象。让我们弄清楚 OO 语言中创建新对象的特殊方法通常被称为什么。
  • 这些方法可能有多种,每种方法采用不同的参数。顺便提一句。你知道这不会编译,对吧?

标签: java class methods


【解决方案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();

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      你需要有一个构造函数来传递参数。我只做了自定义构造函数,要创建你的 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.
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-03
        • 1970-01-01
        • 2020-04-16
        • 2014-08-13
        • 1970-01-01
        • 2021-11-29
        相关资源
        最近更新 更多