aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in overriding" Watch "Doubt in overriding" New topic
Author

Doubt in overriding

Lavanya Raguram
Greenhorn

Joined: Apr 03, 2006
Posts: 27
i have a doubt in this program(K&B pg 104)

class animal
{
public void eat() throws Exception
{}
}
class dog extends animal
{
public void eat(){}
public static void main(String args[])
{
animal a=new dog();
dog d=new dog();
a.eat; //compiler error
d.eat; //ok
}

why is it so?
its not necessary that a overriding method should throw the exception specified in a overriden method right?
Asha Pathik
Ranch Hand

Joined: Feb 08, 2006
Posts: 143
Hi Lavanya,

First of all you are invoking "eat" methods without "()" but I think thats a typo error.

a.eat();
d.eat();

It is absolutely "OK" to decalre an overridding method in subclass that doesn't throw an exception.

But in this program you are invoking the "eat" method using "Animal" class object. Due to polymorphism at runtime Dog class "eat" will get executed but since compiler doesn't know that and thinks that "animal" class eat method may throw an exception, it expects that you must enclose it in try-ctach block.
That's the only problem.

Asha


SCJP 1.5
Lavanya Raguram
Greenhorn

Joined: Apr 03, 2006
Posts: 27
ya sorry actually i missed those braces

so do u mean that for overriding a method with exception declaration we should either enclose the overriding method in a try catch block or declare those exceptions in the overriding method too ?
 
jQuery in Action, 2nd edition
 
subject: Doubt in overriding