• 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 K& B Chapter 2:pg 104 exam watch

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
The valid override says that the overriding method can throw fewer or no exception. However,the below is giving compiler error. As the eat() method is overridden in subclass,then the subclass version of the eat() should be called when we invoke a.eat().

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

class Dog2 extends Animal
{
public void eat() {}
public static void main(String arg[]) {
Animal a=new Dog2();
Dog2 d=new Dog2();
d.eat();
a.eat(); //This line gives compilation error
}
}

Thank you,
Srini
 
Ranch Hand
Posts: 2108
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
what is the error message
 
Srini Krishnan
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is the error message i get while compiling.

Dog2.java:14: unreported exception java.lang.Exception; must be caught or declar
ed to be thrown
a.eat();
^
1 error

Thank you,
Srini
 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Reference type decides about which method signature is choosed during compilation. Since reference a is type Animal and method from Animal class throws Exception you have to wrap invocation it the try/catch block, but during runtime overriding method from the Dog2 class will be invoked.
 
Srini Krishnan
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks,now i got it...
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi srini Could you give me yourcode you had changed?
 
The only cure for that is hours of television radiation. And this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic