File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in overriding" Watch "Doubt in overriding" New topic

Doubt in overriding

Lavanya Raguram

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();; //compiler error; //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.;;

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.


SCJP 1.5
Lavanya Raguram

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, 3rd edition
subject: Doubt in overriding
It's not a secret anymore!