File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

OverLoading

 
sravanthi pulukuri
Ranch Hand
Posts: 125
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
sravanthi pulukuri
Ranch Hand
Posts: 125
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The error is not caused by Dog2's method.

The error is caused by the line

 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic