The code
Animal a = new Dog(); a.eat();
will call the Dog eat
method. But be careful! If you
class Animal { public void eat(Animal victim) { System.out.println("Just ate a cute " + victim.getClass().getSimpleName()); } }
and you have Cat, which defines an additional method:
class Cat extends Animal { public void eat(Mouse m) { System.out.println("Grabbed a MOUSE!"); } }
and then you use them:
Animal cat = new Cat(); Animal mouse = new Mouse(); cat.eat(mouse);
This will print βJust ate a cute mouse,β not βGrabbed a MOUSE!β. What for? Because polymorphism only works for the object to the left of the point in the method call.
source share