2017-09-24 85 views
-2
System.out.println ("\nPolymorphism:"); 
Person[] persons = { new Person("Abu"), 
        new Student ("Ben", 222), 
        new Staff ("Carlo", 3000), 
        new Lecturer ("Donna", 5000, "TCP1101") 
        }; 
for (Person obj: persons) 
    System.out.println (obj.toString()); 
+0

今後,請使用標題爲你的問題的一個簡短的總結,並把實際問題的**身體**的問題。 –

回答

0

這就是所謂的enhanced for statement

for (SomeType foo : iterableElement){ 
    doSomeStuff(foo); 
} 
  • 它會遍歷iterableElement這是類型SomeType /子類型的對象的迭代/陣列SomeType

  • 在循環內部,當前實例將被調用foo,我們將在ea上調用doSomeStuff(foo); CH對象


而且toString();成打印是無用的,代碼會發現它本身

System.out.println (obj); // is good 

使用toString();當你想要把它找回來BU不打印,像:

String foo = myPerson.toString(); 
char firstChar = foo.getCharAt(0); 
+2

正確的名稱是*增強的語句*。 https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2 –

+0

「或類型爲SomeType的對象,」類型爲「SomeType」的元素的「*數組* '(或其子類型)。 –

0

for (Person obj: persons)意味着爲每個元素執行{....}在obj中獲取該對象。

語法:

for (datatype name : array) {...} 
相關問題