2016-11-21 78 views
-3

我想使用對象'arr'的數組訪問變量's'?請參閱代碼片段。如何使用對象數組訪問子類的Instance變量?

public class Array_Chp3 { 
     public static void main(String[] args) { 
     Array_Chp3[] arr = new Array_Chp3[3]; 
     arr[0] = new str(); // when used this line instead of the below line , getting the error "s cannot be resolved or is not a field" 
     //arr[0] = new Array_Chp3(); // when used this line instead of the above line, getting the error s cannot be resolved or is not a field 
     str obj = new str(); 
     System.out.println(arr[0]); 
     System.out.println(arr.length); 
     System.out.println(arr[0].s); // How to access the variable 's'? 

     } 
    } 
    class str extends Array_Chp3{ 
     public String s = "string123 @ str"; 
    } 

錯誤消息: 異常在線程 「主要」 java.lang.Error的:未解決問題彙編: s不能得到解決或不是一個場 在Array_Chp3.main(Array_Chp3.java:17)

+0

你需要一個類str中的getter,它將返回s。那麼你可以把它叫做'arr []。getS();' – XtremeBaumer

+0

你沒有顯示你的'str'類的代碼(它應該用大寫字母「Str」來命名)。它有一個可以從那裏訪問的字段嗎? – SantiBailors

+0

@SantiBailors是的,他確實展示了'str'的​​代碼。閱讀問題。 –

回答

0

如果你知道它是海峽,你可以像這樣將它轉換:

System.out.println(((str)arr[0]).s); 
+1

這不應該工作。如果你閱讀錯誤信息,你會明白爲什麼 – XtremeBaumer

+0

我幾乎肯定這會工作;) – bohuss

+0

@XtremeBaumer是的,它會的。而你對吸氣劑的建議是完全錯誤的。 –

1

你的陣列是Array_Chp3的數組。這意味着你決定這個數組的元素是Array_Chp3的實例。只要它們是Array_Chp3的實例,你並不關心它們具體是什麼類型。

您在第一個元素中存儲的是str實例。這很好,因爲str是一個 Array_Chp3(它擴展了Array_Chp3)。

但由於數組的類型是Array_Chp3 [],編譯器無法保證其元素都是str的實例。它可以保證的是它們是Array_Chp3的實例。

你知道這是一個str雖然,所以你可以告訴編譯器:相信我,我知道它實際上是一個str。這就是所謂的演員:

System.out.println(((str) arr[0]).s); 

但它顯示了一個設計問題。如果您需要將元素作爲str的實例,那麼應將該數組聲明爲str的數組。

+0

非常感謝..它的工作。 –