Please go thru this code.
Animal Class
=======================
class Animal {
public void eat() {
System.out.println("Generic Animal Eating Generically");
}
public void eatanimal() {
System.out.println("In Animal class eatanimal method");
}
}
Horse Class
===============
class Horse extends Animal {
public void eat() {
System.out.println("Horse eating hay, oats, "
+ "and horse treats");
}
public void buck() { }
public void eathorse() {
System.out.println("In Horse class eathorse method");
}
}
Test Animal class
====================
public class TestAnimals {
public static void main (
String [] args) {
Animal b = new Horse();
b.eathorse();
}
}
Error:
testAnimals.java:7: cannot resolve symbol
symbol : method eathorse ()
location: class Animal
b.eathorse();
^
1 error
My QUestion: I am trying to access eathorse(), which is in the class Horse. When I say
Animal b = new Horse(); it is Animal reference and Horse object right ? but why it is looking in class Animal ? Surprisingly if I write the same method in Animal class I am not getting error and I am getting Horse method in Horse class. which is the output " In Horse class eathorse method "
Can anybody pl explain what's going on here ? Thanks very much.