开发者

why cant we overload a method on throws exception basis also?

开发者 https://www.devze.com 2022-12-16 07:18 出处:网络
why cant we overload a method with same return type, name, arguments but with some thro开发者_如何学Pythonws exception? as shown

why cant we overload a method with same return type, name, arguments but with some thro开发者_如何学Pythonws exception? as shown

      public String getAppletInfo(){  }
      public String getAppletInfo() throws Exception{ }


When you call getAppletInfo() in code, how do you want the JVM to choose which overload to call? There is no semantic information in a single method call that allows you to specify which exceptions it should expect.


As per the JLS (Java Language Specification), the Exception thrown is not part of the method signature. Hence both the method definitions you provide don't differ by their signatures and so is not a valid java code.

JLS Section 8.4.9:
If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded

And the method signature is defined as below: Section 8.4.2
Two methods have the same signature if they have the same name and argument type.


If I call myObject.getAppletInfo() which one gets called?


Any method can throw RuntimeException which is a subclass of Exception. So adding a throws Exception is not distinguishing enough for the compiler to choose the right method.


First of all basics of function overloading is that method signature must be different and that includes number of arguments and type of arguments(see docs). So if in two methods if it's just the throwing exception part that is different than that is not counted as function overloading.

The overloaded method can throw any exception thrown / not thrown by the method it overloads because both are independent things.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号