The following code prints "String"
public class Riddle {
public static void main(String[] args) {
hello(null);
}
public static void hello(Object o) {
System.out.println("Object");
}
public static void hello(String s) {
System.out.println("String");
}
}
Why does that code compile? Isn't null ambiguous?
For example, the following code will NOT compile because of an ambiguous signature.
public class Riddle {
public static void main(String[] args) {
hello(null);
}
public static void hello(Object o) {
System.out.println("Object");
}
public static void hello(Integer o) {
System.out.println("Integer");
}
public static void hello(String s) {
System.out.println("String");
}
}
Can someone please explain why the first example can compile without having ambiguous errors?
The result is machine code which is then fed to the memory and is executed. Java code needs to be compiled twice in order to be executed: Java programs need to be compiled to bytecode. When the bytecode is run, it needs to be converted to machine code.
To avoid the problem of duplicated bugs, never reuse code by copying and pasting existing code fragments. Instead, put it in a method if it is not already in one, so that you can call it the second time that you need it.
The "duplicate class" error can also occur when the class is named the same with the same package naming hierarchy, even if one of the classes exists in a directory structure with directory names different than the package names.
If the brackets don't all match up, the result is a compile time error. The fix to this compile error is to add a leading round bracket after the println to make the error go away: int x = 10; System.
In the second case doesn't compile as the compiler can't decide between the method that takes an Integer and the method that takes a String, where as in case of first the compiler can figure it out.
Reference : http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With