user5089861
user5089861

Reputation:

Can i call child class method using parent object?

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

Answers (2)

iavanish
iavanish

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

ShivGames
ShivGames

Reputation: 30

Yes, it will. You are changing the type, so it will work.

Upvotes: 0

Related Questions