domingo, 27 de março de 2011

Question about overloading

When studying for the OCP Java SE 6 Programmer I've get wrong in a question from ExamLab that follows:

Given the code, what will be the result of attempting to compile and run the following program?

public class Lanka {
public Lanka(Object o) {
System.out.println("Object In");
public Lanka(Integer o) {
System.out.println("Integer In");
public Lanka(Number o) {
System.out.println("Number In");
public static void main(String[] args) {
new Lanka(null);

A - Compilation fails
B - Runtime Exception
C - Prints "Object In"
D - Prints "Integer In"
E - Prints "Number In"
F - Prints nothing.

Well. I thought that the first method that appears in my class will be invoked so the answer will be C.
But the right answer is D.
Reading the explanation from ExamLab, I've got that the constructor/method that can take the most subtype instances, will be executed.
But if there was another constructor outside the hierarchy Object<-Number<-Integer, a compile time error will be generated definitely.

It was very tricky question for me, so I've decided to post here.
I hope I can remember it always when coding and doing my certification exam.

Nenhum comentário:

Postar um comentário