是否可以在超类对象上调用子类的方法? [英] Is it possible to call subclasses' methods on a superclass object?

查看:192
本文介绍了是否可以在超类对象上调用子类的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Animal是Dog
的超类,Dog有一种名为bark的方法

Animal is a superclass of Dog and Dog has a method called bark

public void bark()
{
    System.out.println("woof");
}

考虑以下因素:

Animal a = new Dog();
if (a instanceof Dog){
    a.bark();
}

会发生什么?


  1. 不允许分配

  2. 允许对bark进行调用,并在运行时打印woof

  3. 允许对bark进行调用但不打印任何内容

  4. 对bark的调用导致编译时错误

  5. 对bark的调用结果为运行时错误

  1. the assignment isn't allowed
  2. the call to bark is allowed and "woof" is printed at run time
  3. the call to bark is allowed but nothing is printed
  4. the call to bark causes a compile time error
  5. the call to bark results in a run time error

我说2,因为我们正在检查对象是否是狗;因为狗是带有树皮方法的类,如果是,那么我们称它为打印输出:s

I said 2 as we are checking if the object is a dog; as dog is the class with the bark method in it, if it is then we call it which will print out :s

我的理解是否正确?

推荐答案

由于Animal没有名为bark的方法,因此无法编译。想一想,所有的狗都是动物,但不是所有的动物都是狗。所有的狗都吠叫,但不是所有的动物都吠叫。

This won't compile since Animal does not have a method called bark. Think of it this way, all dogs are animals, but not all animals are dogs. All dogs bark, but not all animals bark.

这篇关于是否可以在超类对象上调用子类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆