aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes OverLoading Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "OverLoading" Watch "OverLoading" New topic
Author

OverLoading

sravanthi pulukuri
Ranch Hand

Joined: Mar 15, 2007
Posts: 125
class Animal {
public void eat() throws Exception
{

}
}
class Dog2 extends Animal {
public void eat() { }
public static void main(String [] args)
{
Animal a = new Dog2();
Dog2 d = new Dog2();
d.eat();
a.eat();
}
}
can anyone explain me why is it giving Compiler error
shiva sarna
Greenhorn

Joined: Jul 23, 2006
Posts: 23
Hi,

Here eat() method is overrideen by class Dog2.

Hence according to the overriding rule which version of the method(Animal or Dog2) will be called will de determined at run time depending on the object type and not at compile time.

If the supertype has declared a checked exception the compiler will think that supertype's version is called( in this case Animal's eat method) hence this exception should be caugth.

The following code will compile fine:

class Animal {
public void eat() throws Exception
{

}
}
class Dog2 extends Animal {
public void eat(){ }
public static void main(String [] args)
{
Animal a = new Dog2();
Dog2 d = new Dog2();
d.eat();
try
{
a.eat();
}
catch(Exception e){}
}
}


So even at run time Dog2's eat() version is called at compile time the compiler thinks it is calling Animal's version.

Remember which overridden method is called is determined at runtime and not compile time.

regards

Shiva


SCJP 5.0
sravanthi pulukuri
Ranch Hand

Joined: Mar 15, 2007
Posts: 125
What i thought is the overriding method sholdnt declare any checked exceptions of its owns
So DOG2 s method sholdnt give any error but why is it giving?is that we are using polymorphic assigment?
Please corerct me if iam wrong
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
The error is not caused by Dog2's method.

The error is caused by the line

 
 
subject: OverLoading