[英]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.
在主要方面,我想创建PARENT类的obj并调用子类的方法。 So, is it possible or not?
那么,有可能吗? I have also used
instanceOf
to just check relationship 我也用过
instanceOf
来检查关系
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();
}
}
Your code should work fine. 您的代码应该可以正常工作。 The if condition will result in false, so your animal will not walk().
if条件将导致false,因此您的动物将不会walk()。
Animal animal = new Animal();
This animal will have all the behaviours of Animal, ie eat(), but none of the behaviours of the sub-class Cat, ie walk(). 该动物将具有动物的所有行为,即eat(),但不具有子类Cat的行为,即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的所有行为以及Cat的所有行为,则需要实例化Cat类。
Animal animal = new Cat();
Now your animal will eat and walk. 现在,您的动物将进食和行走。
Yes, it will. 是的,它会的。 You are changing the type, so it will work.
您正在更改类型,因此它将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.