Consider the following scenario:
interface Animal { } class Dog implements Animal{ public void dogMethod() {} } class Cat implements Animal{ public void catMethod() {} } public class Test { public static void test (Animal a) { System.out.println("Animal"); } public static void test (Dog d) { System.out.println("Dog"); } public static void test (Cat c) { System.out.println("Cat"); } public static void main(String[] args) { Animal a = new Cat(); Animal d = new Dog(); test(a); } }
If test (a) printed βCatβ and not (correctly) βAnimalβ simply because it contains a reference to the Cat object, then you can call catMethod () on the Animal object, which makes no sense, Java selects the most applicable a method based on a type that is not related to a variable.
source share