I've just started learning object oriented programming from the book head first java.It said that polymorphism enables me to create an array of the superclass type and then have all the subclasses as the array elements.But when I tried writing code using the same principles it ran into error saying
error: cannot find symbol
I made the classes the superclass was animal and the dog class extended the animal class having a fetch method of its own, but when I referenced the dog variable as animal it did not work here is the code
The Animal class:
public class animal{
String family;
String name;
public void eat() {
System.out.println("Ghap Ghap");
}
public void roam() {
System.out.println("paw paw");
}
}
The dog class:
public class dog extends animal {
public void fetch() {
System.out.println("Auoooooooo");
}
}
The Tester class:
public class tester {
public static void main(String args[]){
animal doggie = new dog();
doggie.fetch();
doggie.eat();
doggie.roam();
}
}
The error:
tester.java:4: error: cannot find symbol
doggie.fetch();
^
symbol: method fetch()
location: variable doggie of type animal
1 error
Edit: Last time I asked this question I went home thinking the object doggie
is of the type animal
and it has no idea of about the fetch()
function that has been declared in the dog
class. But adding the line
System.out.println(doggie.getClass().getName());
Gives dog
as the type of the class, if dog
is indeed the type of the class, shouldn't it have the knowledge of the method declared within it
?