有麻烦创造这个对象

时间:2014-01-21 16:16:25

标签: java

我是java的新手,并试图掌握使用两个不同的值创建一个对象。 我正在尝试创建一个名为customer的Customer对象,初始值为1和cust1,然后使用toString()将客户对象显示到输出

感谢您提前提供任何帮助。

这是我目前所拥有的。

public class Customer {

private int id;
private String name;





public Customer(int id, String name) {
    this.id = id;
    this.name = name;
    Customer customer = new Customer(1, "cust1");
}

2 个答案:

答案 0 :(得分:0)

不要在类构造函数中创建新的对象实例 - 这将导致StackoverFlowException

public class Customer {

    private final int id;
    private final String name;

    public Customer(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

在单独的类中,您只需使用

创建一个新实例
Customer customer = new Customer(1, "Name");

答案 1 :(得分:0)

你的程序没有入口点,你的课程应该是这样的

public static void main(String[] args)
{
 //objects created here
}

您还可以创建Customer对象作为Customer类的成员,这意味着每个Customer对象都包含另一个对象。

您无法设置此类<{p}}成员

Customer

就像这样(如果他们在正确的地方,如上所述)

Customer customer = new Customer(); //you also don't have a no argument constructor
customer = 1; //how would it know where to put this 1?
customer = cust1; //same as above

或者像这样

Customer customer = new Customer(); //if using this method you will need a no argument constructor
customer.id = 1;
customer.name = cust1;

摘要

  • 您需要一个入口点
  • 您正在使用无参数构造函数创建new Customer(1,"cust1"); ,但您只有一个具有两个参数的构造函数
  • 您出于某种原因 - 在每个Customer
  • 内创建Customer
  • 您没有以正确的方式(甚至是有效的方式)设置Customer个对象的成员