• Post Reply Bookmark Topic Watch Topic
  • New Topic

Method overriding in Java  RSS feed

 
pinky suresh
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a doubt in method overriding. If a superclass has a method that throws an Excpetion and the same method is overridden in subclass & the overridden method does not throw any exception, still that method should be called within try catch block in the implementing class. Why is it so??
See below example for clear idea on my doubt.

public class Shape
{
public void displayShape() throws Exception
{
System.out.println("displayShape in superclass ");
}
}

public class Circle extends Shape
{
public void displayShape()
{
System.out.println("displayShape in circle");
}

public static void main(String[] args)
{
Shape c = new Circle();
c.displayShape();
}
}

Compiler says to sorround Circle's displayShape() in a try-catch block. Please let me know why this method should be sorrounded with try-catch block even when the overridden method in Circle class does not throw any Exception.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, it's not Circle's displayShape() that you're asking for. Look at those two lines again:



"c" is of type "Shape". The compiler does not know, or care, the exact kind of object that's in c at that point. All it knows is that it's some kind of Shape, and Shape.displayShape() declares an exception.

If you change these two lines just a tiny bit:



You will not be required to use a try block. Here, the compiler knows that c is a Circle, and so it lets you call the method withot worrying about an exception.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!