Saturday, September 28, 2019

Java Output Questions

1. public class Test {

public void foo(Object o) {
System.out.println("Object");
}

public void foo(String s) {
System.out.println("String");
}
public static void main(String[] args) {
new Test().foo(null);
}

}

bove program compiles perfectly and when we run it, it prints “String”.

So the method foo(String s) was called by the program. The reason behind this is java compiler tries to find out the method with most specific input parameters to invoke a method. We know that Object is the parent class of String, so the choice was easy. Here is the excerpt from Java Language Specification

If more than one member method is both accessible and applicable to a method invocation … The Java programming language uses the rule that the most specific method is chosen.

The reason I am passing “null” is because it works for any type of arguments, if we pass any other objects the choice of method for the java compiler is easy.






You will get compile time error as The method foo(Object) is ambiguous for the type Test because both String and Integer class have Object as parent class and there is no inheritance. So java compiler doesn’t consider any of them to be more specific, hence the method ambiguous call error.


public class Test {

public void foo(Object o) {
System.out.println("Object");
}

public void foo(Exception e) {
System.out.println("Exception");
}

public void foo(NullPointerException ne) {
System.out.println("NullPointerException");
}

public static void main(String[] args) {
new Test().foo(null);
}

}
As above explained, here foo(NullPointerException ne) is the most specific method because it’s inherited from Exception class and hence this code compiles fine and when executed prints “NullPointerException”.

No comments:

Post a Comment