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

标签 java inheritance instanceof downcast

我创建了基类动物和子类作为猫。 在main中,我想创建父类的obj并调用子类的方法。 那么,到底可不可以呢? 我还使用 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();  
}
}

最佳答案

您的代码应该可以正常工作。 if 条件将导致 false,因此您的动物将不会 walk()。

Animal animal = new Animal();

该动物将具有 Animal 的所有行为,即 eat(),但不具有子类 Cat 的任何行为,即 walk()。

如果你想让你的动物拥有Animal的所有行为以及Cat的所有行为,你需要实例化Cat类。

Animal animal = new Cat();

现在您的动物可以进食并行走。

关于java - 我可以使用父对象调用子类方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42692902/

相关文章:

java - Object 是抽象类的父类(super class)吗?

java - 以通用方式使用 instanceof

Java:在列表中添加或删除元素时避免使用 'instanceof'

java - 使用 jdbc 和 Kerberos 委派连接到 SAP HANA 数据库

java - 批处理文件以运行带有参数的jar文件

java - 我不知道 Eclipse 中的数组发生了什么

java - 在 Java 中写入二进制文件

ios - 外部继承重复符号错误,这是怎么回事?

c# - 用c#泛型继承,而继承类类型

java - 为什么 `instanceof` 错误而不是在用于 2 个不兼容的类时返回 `false`?