This is called polymorphism and is one of the most powerful aspects of Java.
Polymorphism allows you to process different objects in the same way.
This is a great way to create reusable, flexible code.
Unfortunately, this is part of Java that new programmers often use for understanding.
The example you provided includes inheritance (class extension).
Another way to take advantage of polymorphism is to use interfaces.
Different classes that implement the same interface can be handled the same way:
class Dog extends Animal implements Talker { public void speak() { System.out.println("Woof woof"); } } class Programmer implements Talker { public void speak() { System.out.println("Polymorphism rocks!"); } } interface Talker { public void speak(); } public static void testIt() { List<Talker> talkerList = new ArrayList<Talker>(); talkerList.add(new Dog()); talkerList.add(new Programmer()); for (Talker t : talkerList) { t.speak(); } }
source share