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.
精彩评论