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());
Asked
Active
Viewed 465 times
2 Answers
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 typeSomeType
/subtype ofSomeType
inside the loop, the current instance will be called
foo
, and we will calldoSomeStuff(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
-
2The correct name is an *enhanced for statement*. https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2 – Andy Turner Sep 24 '17 at 14:27
-
"or object of type SomeType," an *array* with elements of type `SomeType` (or a subtype thereof). – Andy Turner Sep 24 '17 at 14:30
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