Reputation: 197
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
}
}
Upvotes: 0
Views: 44
Reputation: 6117
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.
Upvotes: 1
Reputation: 467
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.
Upvotes: 0
Reputation: 2371
The reference type of the variable m
is Animal so at compile time, the method signature from the class Animal is used, event though when running the code, the actual method called is the one from the subclass.
Upvotes: 1