• 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

Method overriding in Java

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic