2014-01-21 77 views
-1

我对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"); 
} 
+1

那么,有什么问题呢? –

回答

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"); 
0

只需创建一个新的实例你没有入口点到您的程序,这看起来应该像这样在你的类

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

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

你不能设置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但你只有它有两个参数一个构造
  • 您是 - 对于一些reason-每Customer
  • 内创建 Customer
  • 你没有设置你的Customer对象的成员在正确的(甚至是在一个有效的)方式
+0

我没有切入点,因为这是一个单独的课程,我有一个主要课程。我应该如何将我的Customer对象放在我的构造函数中?我编辑了我的主帖。 – Tonno22

+0

你不应该在你的'Customer'类中创建你的'Customer'(不是为了你的目的)。它应该由另一个类或者在你的入口点方法中创建。 –

+0

你想在哪里使用Customer对象?那就是你应该创建一个Customer对象的地方。可能在你的主课堂上。 –