Reputation:
I have created base class animal and child class as cat.
In main, I want to create obj of PARENT class and call the method of child class.
So, is it possible or not?
I have also used instanceOf
to just check relationship
public class Animal
{
public void eats()
{
System.out.println("Animal Eats");
}
}
public class Cat extends Animal
{
public void walks()
{
System.out.println("Cat Walks");
}
}
public class AnimalMain
{
public static void main(String args[])
{
Animal a=new Animal();
display(a);
}
public static void display(Animal a)
{
a.eats();
if(a instanceof Cat)
((Cat)a).walks();
}
}
Upvotes: 0
Views: 1075
Reputation: 509
Your code should work fine. The if condition will result in false, so your animal will not walk().
Animal animal = new Animal();
This animal will have all the behaviours of Animal, i.e. eat(), but none of the behaviours of the sub-class Cat, i.e. walk().
If you want your animal to have all the behaviours of Animal as well as all the behaviours of Cat, you need to instantiate the Cat class.
Animal animal = new Cat();
Now your animal will eat and walk.
Upvotes: 3