• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Whether the derived class method can throw a exception while overriding?

 
srinivas sridaragaddi
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.io.*;

class animal
{
public void eat() throws Exception
{
System.out.println("animals eat");
}
}

class horse extends animal
{
public void eat()
{
System.out.println("horse eat");
}

}

public class test
{
public static void main(String[] args)
{
animal a =new horse();
horse b=new horse();
a.eat();
b.eat();
}
}

This code will not compile because the exception declared on animal eat() method.This happens even though at run time, the eat() method used would be of horse version.Which does not declare any exception.


K&B book pg no 104

Can any one explain how it's working

My doubt is in overriding can we throw a exception? i didnt get the explanation and also please explain the above.

Thanks in advance
 
Bob Ruth
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I went and looked at that reference in the K&B and here is how I interpret it....

in your two delcarations.....

animal a =new horse(); <---- THIS is causing the problem
horse b=new horse();

The explanation that I read says that IF you use a SUPERCLASS reference to refer to the SUBLCLASS object then the compiler is going to initially assume that you are calling a SUPERCLASS object. ( I know that with polymorphism, the overridden method would be selected at run-time, but it appears that the compiler at least looks at the operation as it is coded) Based on that assumption, a SUPERCLASS reference to an object that is DECLARED as a subclass and does not have compatible Exception handling, causes a compile time error.

I would think that, for a test, comment out the superclass declaration of the subclass type and see if it compiles.

Essentially I guess that means that, if you are going to have superclass type references referring to subclass types then the subclass must declare the exception according to the proper rules for overriding.
 
camilo lopes
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you flame a method that can launch an exception the method that is calling must declare the exception or treat, its metodo main() does not make none nor another one therefore that codigo does not compel.
* this for exceptions only verified.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic