| Author |
overloaded method are free to throw new checked exception but not overriding method?
|
samdeep aarzoo
Ranch Hand
Joined: Jun 09, 2005
Posts: 160
|
|
overloaded method are free to throw new checked exception but not valid for overriding method. can anyone explain me how by an example?
|
 |
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
|
|
Questions like this are often well explored by experiment. Warning - some of these experiments won't even compile! Make a class A with a method "test(String x)" that just displays any string passed in. Make a class B that extends A with two methods: "test(String x) throws Exception" and "test(int x) throws Exception". Then try some tests like these. The string argument method in B is an override. When you call an instance of B with a string you run the override method, not the original. The compiler will not let you add on more checked exceptions when you override. The int argument method in B is an overload. You started out saying the compiler would allow it to add new exceptions. Did it? I'm being a little tricky - you asked for examples and I asked you to build your own examples. You didn't ask for an explanation of why it works this way. After you get your examples going, let's talk more about why.  [ June 18, 2005: Message edited by: Stan James ]
|
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
|
 |
manishsharma sharma
Greenhorn
Joined: Jun 17, 2005
Posts: 24
|
|
Thanks Stan James, u r example is really good, i have worked on it. In case of overriding a method compiler will not allow us to add Exception but In case of overloading it allows us to throw Exception which is not thrown By original. But one more problem is occured the line A three= new B(); three.test(1);// this line is not compiled throwing error can we not call overloaded method of derived class throgh base class objedt just as we done in case of method overriding? why? plz ........remove my doubt
|
Thanks, Manish
SCJP-100, SCMAD-91, SCWCD-89, http://javatechtips.blogspot.com/
|
 |
samdeep aarzoo
Ranch Hand
Joined: Jun 09, 2005
Posts: 160
|
|
thanks james for this wonderful explanation i made the class according to u _____________________________________ class A { public void test(String s) { System.out.println(s); } } class B extends A { public void test(String s) { System.out.println(s); } public void test(int i )throws Exception { System.out.println(i); } } public class C { public static void main(String args[]) { B t =new B(); t.test("hello"); // t.test(1); } } _______________________________________________ i check output with different conditions and get my answer and that clear my all doubts i thanks once again for this wonderful explanation
|
 |
 |
|
|
subject: overloaded method are free to throw new checked exception but not overriding method?
|
|
|