• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Doubt in overriding

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?
 
If I had asked people what they wanted, they would have said faster horses - Ford. Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic