简体   繁体   中英

method throws exception in parent overridden by subclass

Why an instance of subclass referenced to parent class needs to catch the exception if the instance method was overridden by subclass. here's the illustration for clear picture

public class Animal{
  public void printName() throws Exception{
   System.out.println("Animal Method");
  }
}


public class Dog extends Animal{

  public void printName(){
     System.out.println("Dog Method");
  }
  public static void main(String[] args){

    Animal m = new Dog();
    ((Dog)m).printName(); //prints Dog Method
    m.printName(); // this is supposed to be overridden and will print "Dog Method", why the throws Exception of Animal method printName was copied. to the instance

  }
}

变量m的引用类型是Animal,因此在编译时,使用了Animal类的方法签名,尽管在运行代码时,调用的实际方法是子类中的方法。

Its because the variable m is defined as an Animal, and the compiler sees that Animal's printName method throws an exception.

You may know that which methods you can call on a variable are defined by its type, Compile time type Declaration like:

Animal m;

Even if m actually points to a dog, you can only call methods of Animal on m. ( Unless you cast )

In the same way, which exceptions it might throw is also defined by its declared type. That is why when you call the method on a Dog declared object, you are not required to catch the exception.

What is really interesting to know, is that the overriding method in the derived class can only remove exceptions from the throws clause, or make them more specific, but not add any, as that would lead to surprising results for someone calling the method on the base class.

In compile time the m is actually of Animal type, so yo should catch the Exception since the Exception is checked and there is not dog object in compile time, but in runtime the m is of Dog type. so the dog printName method will invoked, but in this line ((Dog)m).printName() you cast it to Dog so it will not necessary to catch the Exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM