public class Overload { public static void main(String args[]) { int result = foo(new B(), new B()); System.out.println(result); } public static int foo(A a, B b) { return 1; } public static int foo(B b, A a) throws Exception { return 2; } static class A { } static class B extends A { } }
Without using a compiler (using the JLS and JLS report is allowed), answer the following:
- Does this code compile?
- If yes - what is the result from running the program?
- If no - why not? List all errors.
Answers on a postcard.
No. The compiler will be unable to work out unique signatures (or whatever they're called) for the methods.
Mmm, correct. The "throws Exception" was just to confuse people - although the defined exception sometimes feels like part of the signature.
So the code is incorrect because of the presence of "override-equivalent signatures." (See
http://java.su… for a more formal treatment)
Sorry, I am struggling to work out where an exception would be considered to be part of the signature - that would suggest that the following two would be a "good" compile:
<code>
private int foo ( int a ) { return 1; }
private int foo ( int a ) throws Exception { return 1; }</code>
Unfortunatly, Ive found a problem in C#, which is legal in terms of the language, but obviously bad:
<code>
class foo {
public int bar(){
return 1;
}
public static int bar() {
return 2;
}
}</code>
In this instance, when coding inside a function in the class, static and non-static functions can both be referenced without a this. However, in this case, it is unclear which one actually would run:
<code>
this.bar() == 1;
foo.bar() == 2;
bar() -> ?</code>
What is interesting, is that the compiler treats the two sets of results differently, and therefore the signatures do not need to be similar. The static could return a string, and the non-static an int.
Fun.
code will not complie