skip to main |
skip to sidebar
Overridden Methods
class Animal {
public void eat() {
System.out.println("Generic Animal Eating Generically");
}
}
class Horse extends Animal {
public void eat() {
System.out.println("Horse eating hay, oats and horse treats");
}
public void buck() { }
}
public class TestAnimals {
public static void main (String [] args) {
Animal a = new Animal();
Animal b = new Horse(); //Animal ref, but a Horse object
a.eat(); // Runs the Animal version of eat()
b.eat(); // Runs the Horse version of eat()
b.buck(); // Can't invoke buck(); Animal class doesn't have that method
}
}
Reason: The compiler looks only at the reference type, not the instance type.
No comments:
Post a Comment