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

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

问题描述

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 导致运行时错误

我说 2,因为我们正在检查对象是否是狗;因为 dog 是包含 bark 方法的类,如果是,那么我们调用它,它将打印出来 :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天全站免登陆