为什么不能调用bark方法 [英] Why bark method can not be called

查看:312
本文介绍了为什么不能调用bark方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Animal{
    void run() {
    }
}
class Dog extends Animal {
    void bark() {
    }
}
class Testing{
    public static void main(String[] args)  {
        Animal d = new Dog();
        d.run();
        d.bark();
    }
}

我试图用狗的对象调用bark方法class的引用存储在Animal类变量中。但它显示我编译时错误。任何人都可以解释为什么?

I am trying to call bark method using object of dog class whose reference is stored in Animal class variable. But it is showing me compile time error. Can anyone explain Why?

推荐答案

这就是它的工作方式。

当编译器尝试检测谁是 d 。?它见。

When compiler try to detect who is d.? its see.

Animal d

编译器不知道它是如何创建的,看一下引用类型。因此, d Animal

Compiler doesn't know know how its created, look at the reference type. So, d is an Animal.

现在引用是 Animal Animal 是否有 bark()方法?没有。 错误

Now the reference is Animal. Does Animal have a bark() method? no. ERROR.

可能 d inside但编译器不知道,编译器不应该知道,在这种情况下,编译器会翻译你所说的关于 d 的内容。这就是你收到错误的原因。

May be d is a Dog inside but compiler doesn't know that and compiler shouldn't know, Compiler translate what you said about d in that case. That's why you getting the error.

现在你可以告诉我想要 d 作为因为我知道 d by,

Now you can tell that I want d to act as Dog because I know d is a Dog by,

((Dog) d);

然后拨打 bark()

((Dog) d).bark();

因此编译器将 d 作为 Dog 仅适用于此操作。

So compiler will take d as a Dog only for this operation.

这篇关于为什么不能调用bark方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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