Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding doubt in K&B

 
Siri Naray
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello ranchers,

In K&B Rules for overriding a method - page 102 last point

"The Overriding method can throw newer or fewer exceptions.
Bottom Line: an Overriding method does'nt have to declare any exceptions that it will never throw, regardless of what the overridden medhod declares."

If this is right, why should you get a compiler error with the following code?

page 104 Exam Watch

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

class Dog2 extends Animal {
public void eat(){ // No exceptions }
public static void main(String [] args) {
Animal a = new Dog2();
Dog2 d = new Dog2();
d.eat();
a.eat(); //compiler error- unreported exception
}
}

This code will not compile because of the Exception declared on the Animal eat() method. This happens even though, at runtime, the eat() method used would be the Dog version, which does not declare the exception.

Can anyone please explain. For be both look so contradicting.

Thank you
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Variable a is a reference to an Animal, so it is Animals eat() method which is being checked for exceptions by the compiler. Animals.eat() declares it throws Exception but you do not catch them or declare that your main method throws them.
 
abhijit Ohal
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Overriding is done at runtime by jvm.But compiler will see the refernce variable i.e Animal class & invoke public void eat() throws Exception{} but at that time compiler Notice that exception is not handle. So it is giving exception. Definately it will call Dog2 's eat if you follow overriding rules.
 
Siri Naray
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So what should I do for this code not to generate any compiler error? Just handle the exception?
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Handle it by try/catch or put it in throws clause in main method.

Naseem
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic