Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in overriding

 
Lavanya Raguram
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Lavanya Raguram
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic