error: non-static method newAnimal() cannot be referenced
This might be obvious error to all programmers but i am new to programming and cannot find out what is going on. I have 3 classes (Animal, Fox, and Rabbit). I can get the code to compile using instanceof() but I am trying to use polymorphism to replace certain code but cannot get it to compile. Here is the code:
Animal code is:
Code:
public abstract class Animal
{
public Animal newAnimal(){
Animal babyAnimal;
if (this instanceof Rabbit){
babyAnimal = new Rabbit(false);
}else{
babyAnimal = new Fox(false);
}
return babyAnimal;
}
}
Rabbit code is:
Code:
public class Rabbit extends Animal
{
public Animal newAnimal() {
return new Rabbit(false);
}
}
Fox code is:
Code:
public class Fox extends Animal
{
public Animal newAnimal() {
return new Fox(false);
}
}
So when I try to replace the instanceof() code in Animal with Rabbit.newAnimal I get that error saying:
non-static method newAnimal() cannot be referenced from a static context
so this is the new code i am trying to use in Animal in its place:
Code:
public Animal newAnimal(){
Animal babyAnimal;
if (Rabbit.newAnimal()){
Rabbit.newAnimal();
}else{
Fox.newAnimal();
}
return babyAnimal;
}