Java – why are there unhandled exceptions in this code?

I am from the following code:

class Animal{
    public void eat() throws Exception {}
}

class Dog extends Animal{
    public void eat(){} //no exception thrown
    public static void main(String[] args){
          Animal a = new Dog();
          Dog d = new Dog();
          d.eat();   //ok
          a.eat();  //does not compile!..(1)
    }
}

Here, (1) dog's eat () method will not be compiled even at runtime Why is that? Why does Java support this? Shouldn't this be a bug?

Solution

Because you use the animal reference to reference dog Animal. The signature of eat includes exception The compiler knows that dog is an animal, but once you use animal to reference it, you don't know it is a dog until runtime

In other words, all dogs are animals, but not all animals are dogs

edit

You can add an actor

((Dog) a).eat();  //would compile

At runtime, if a is not actually a dog, it will fail

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>