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
When using polymorphism, if you create an instance of the subclass and store its reference in a variable of superclass type, you can only call those methods on the newly created instance which are present in the super class.
In your code, you created an instance of dog
class and stored its reference in doggie
which is of type animal
(super class of dog), In such case, you can't call any method on dog
class instance that isn't available in animal
class.
fetch
method is not defined in the animal
class hence you get the error.
Solution
Either define the fetch
method in the animal
class
OR
change
animal doggie = new dog();
to
dog doggie = new dog();