简体   繁体   English

我可以使用父对象调用子类方法吗?

[英]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.

相关问题 如何在Java中使用Child对象调用Parent类的方法 - How to call method of Parent class using Child object in Java 将父对象向下转换为子对象后,如何调用子方法? - How can i call the child method after downcasting parent object to child object? 如何使用子类引用使用父关键字调用父类方法以创建对象? - How to call a parent class method using child class reference using super keyword for object creation? 调用子类的父类方法 class object java - call parent class's method on a child class object java 从父类对象调用子类方法 - Call a child class method from a parent class object 如何在JAVA中从父类的内部类中调用子类中的重写方法? - How can I call the overridden method in a child class from a parent class's inner class in JAVA? 为什么在父类中必须强制有一个子方法以引用父类的引用来调用它,该父类引用子类的对象? - Why is it mandatory to have a child method in Parent class to call it with a reference of parent class which is referring to an object of child class? 父类可以在Java中调用动态创建的子类方法吗? - Can Parent Class call Dynamically created child class method in java? 我可以直接在Java的子类中调用父类的实例方法吗? - Can I call instance method of a parent class directly in child class in Java? 无法使用任务栏图标从子类调用父类的方法 - Can't call method of parent class from child class using tray icon
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM