-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());
azro
  • 53,056
  • 7
  • 34
  • 70
Engineax
  • 1
  • 3

2 Answers2

0

This is called a enhanced for statement

for (SomeType foo : iterableElement){
    doSomeStuff(foo);
}
  • it will iterate over iterableElement which is an iterable/array of object of type SomeType/subtype of SomeType

  • inside the loop, the current instance will be called foo, and we will call doSomeStuff(foo); on each object


Also toString(); into a print is useless, the code will go find it itself

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

Use toString(); when you want to get it back bu not in a print, like :

String foo = myPerson.toString();
char firstChar = foo.getCharAt(0);
azro
  • 53,056
  • 7
  • 34
  • 70
0

for (Person obj: persons) mean that for every element of persons execute {....} taking that object in obj.

syntax:

for (datatype name : array) {...}
Piyush Mishra
  • 327
  • 1
  • 11