2015-10-02 82 views
0

我想讓我的程序從另一個類中輸入一個私有變量。Mutator和Accessor(使用繼承)

我想使用mutator和accessor。

它保持錯誤NullPointerException。我的代碼中有什麼問題?

public abstract class Inputs { 
private String val; 
private String typ; 
public abstract void setVal(String val); 
public abstract void setTyp(String typ); 
public abstract String getVal(); 
public abstract String getTyp(); 
} 

public DeckOfCards extends Inputs{ 
String val; 
String typ; 
static DeckOfCards kerds = new DeckOfCards(); 
    public void setVal(String val){ 
     this.val = val; 
    } 

    public void setTyp(String typ){ 
     this.typ = typ; 
    } 

    public String getVal(){ 
     return this.val; 
    } 

    public String getTyp(){ 
     return this.typ; 
    } 
    public static void main(String args[]){ 
     System.out.print("Value: "); 
     kerds.setVal(kerds.val); 
     if(kerds.val.equals("A"){ 
      System.out.print("Type: "); 
      kerds.setTyp(kerds.typ); 
     } 
    } 
} 
+0

你的堆棧跟蹤在哪裏? –

+0

什麼是堆棧跟蹤? – Mariel

+0

控制檯中的完整錯誤:http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-錯誤 –

回答

1

這是你的問題kerds.setVal(kerds.val);kerds沒有創建然而,當主運行。

  • 你需要使用它之前初始化DeckOfCards的實例。
  • 只有在設置後才嘗試檢索值。別的reteive上尚未設置將拋出一個NullPointerException(正如拉赫曼指出)的值

這裏的嘗試是正確使用的例子:

 public static void main(String args[]){ 
     DeckOfCards kerds = new DeckOfCards(); 
     kerds.setVal("A"); 
     kerds.setTyp("TYPE_A"); 

     System.out.println("Displaying values of kerds"); 
     System.out.println("kerds value : " + kerds.getVal()); 
     System.out.println("kerds type : " + kerds.getTyp()); 
     } 
+0

如果用戶必須先輸入它,該怎麼辦?我應該使用kerds.val = input.next(); ? – Mariel

+0

獲取鍵盤輸入,請看下面這個:http://stackoverflow.com/questions/17538182/getting-keyboard-input – cjcroix

+0

如果您發現這個答案有用,您可以接受它,否則隨時投它: )http://stackoverflow.com/help/why-vote – cjcroix

0

kerds.setVal(kerds.val)被設置空值。此時kerds.val的值尚未設置。基本上你的代碼沒有任何意義。您正在設置一個屬性值爲尚未設置的相同屬性。