I like homework, but I'm bored, and Java makes me nostalgic.
List<A> list = new ArrayList<A>();
list.add(new A());
list.add(new A());
list.add(new B());
public void printAll() {
for(A i : list) {
System.out.println(i.print());
}
}
class A {
public String print() {
return "A";
}
}
class B extends A {
@Override
public String print() {
return"B";
}
}
The result will look like this:
A
A
B
The polymorphic part is when different code is executed for the same method call. The loop does the same thing every time, but actually you can call different instance methods.
Cogsy source
share