Why is there an Unhandled Exception in this code?

I came up with 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) does not compile even if eat () is called at runtime. Why is this happening? What is the reason Java supports this? Shouldn't this be logged as a bug?

+3


source to share


3 answers


Since you are using the link Animal

to link to Dog

. And the signature Animal.eat

includes Exception

. The compiler knows what Dog

is kind Animal

, but once you use the link Animal

, it doesn't know what it is Dog

until runtime.

In other words, all Dog

(s) are Animal

(s), but not all Animal

(s) are Dog

(s).

Edit



You could add a cast

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

      

This will happen a

at run time if it really isn't Dog

.

+7


source


Animal a = new Dog();

      

in OOP (Object Oriented Programming)

, it's called polymorphism

. And in Java (and mostly in an OOP support language like C #) this behavior is a compilation check. This means that the compiler at compile time just knows what it is, and it cannot know what it is before .

For example:

Animal a = new Dog();
a.bark(); // cannot. because compiler doesn't know a is a dog until runtime
((Dog)a).bark(); // yes. we say to compiler: a **must** be a dog

      



Another example:

    Animal a = new Cat();
    // yes. can compile. we force compiler to know this animal is a dog. 
    //but will run-time exception because in fact this is a cat
    ((Dog)a).bark(); 

      

Hope this help :)

+3


source


First, you are not following the Method Override rules . if the base class method throws any exception, then the child class method should throw an equal or low level exception. now this code will work fine because it follows the rule override method. Also, @Elliot is telling the truth, the compiler is not aware of the dog object (as Animal points out) at compile time. it will only resolve at runtime.

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

class Test extends Animal{
  public void eat()throws Exception{} 
  public static void main(String[] args)throws Exception{
      Animal a = new Test();
      Test d = new Test();
      d.eat();
      a.eat();  
}
}

      

+3


source







All Articles