2014-01-21 76 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對象的地方。可能在你的主課堂上。 –