Animal can't call a Horse method, even if it's overridden in Horse.
Oops, I was wrong in my last post. If you change the private drink() method in Animal to public, it does call the public drink() method in Horse. So, perhaps, since the method in Animal was marked private, the Horse class did not have access to it, and could not override it.
Are the drink() methods considered overloads? (I don't think so)
The reason I ask is because they act just like overloads in the situations I've tested them in. They use the reference type to determine which drink()method to run. When drink() is called in Animal, the only way it can execute the Horse drink() method is to use a Horse type reference variable, or a reference variable that is cast to a Horse type.
class Animal {
private void drink() {
System.out.println("Animal drinks");
}
public void calldrink(Animal a) { //1-Change Animal to Horse - try it,
a.drink(); // 2-then cast a to Animal <((Horse)a).drink()>, try it.
}
}
class Horse extends Animal {
public void drink() {
System.out.println("Horse drinks");
}
}
class Test2 {
public static void main(String[] args) {
Horse a = new Horse();
a.calldrink(a);
}
}
1.) Do the below lines create two instances on the heap, one for the horse and one for the animal?
code:
class Horse extends Animal
// class header and main method
Animal a = new Horse();
// close main and class
3.) If you change the drink method in Horse to private the cast of animal to horse doesn't work. Why is that, don't you get don't you get the private methods of the original class? Through testing it does not appear that way but I'm not sure why.