I am only learning about polymorphism so be easy on me (literally copying from the book). I try to pass a class as an argument to a method. When I do that I can call the superclass methods, but not the actual subclass. Using the start() method, I try to make the wolf howl:
public class experiment {
public static void main(String[] args) {
PetOwner own = new PetOwner();
own.start();
}
}
//Trying polymorphic arguments
class Vet {
public void giveShot(Animal a) {
a.howl();
}
}
class PetOwner {
public void start() {
Vet v = new Vet();
Wolf w = new Wolf();
v.giveShot(w);
}
}
//Inheritance//
//Kingdom - Animal
class Animal {
public void move() {
System.out.println("*motions softly*");
}
}
//Family - canine
class Canine extends Animal {
public void bark() {
System.out.println("Woof!");
}
}
//Species - wolf
class Wolf extends Canine {
public void howl() {
System.out.println("Howl! Howl!");
}
}
If I pass the howl method to the superclass (Animal) it works fine. If I call it directly from the Wolf class - it works fine. The only instance where it doesn't work is if I try to pass the wolf class as an argument and call it from there.
Here is why I try it that way, quoted from Head First Java pg 187:
The Vet's giveShot() method can take any Animal you give it. As long as the object you in as the argument is a subclass of Animal, it will work
I am getting a "cannot find symbol symbol: method howl(), Location variable of type animal" error.