Sunday, September 22, 2024
Google search engine
HomeLanguagesJavaJava Function/Constructor Overloading Puzzle

Java Function/Constructor Overloading Puzzle

Predict the output of the program




public class GFG {
    private GFG(Object o) {
        System.out.println("Object");
    }
    private GFG(double[] d) {
        System.out.println("double array");
    }
    public static void main(String[] args) {
        new GFG(null);
    }
}


Solution:
The parameter passed to the constructor is the null object reference and arrays are reference types too. If we try running the program, we get following.
The program prints double array.

We can notice that the compiler doesn’t cause ambiguous call error. Java’s overload resolution process operates in two phases.
The first phase selects all the methods or constructors that are accessible and applicable.
The second phase selects the most specific of the methods or constructors selected in the first phase. One method or constructor is less specific than another if it can accept any parameters passed to the other.
In our program, both constructors are accessible and applicable. The constructor GFG(Object) accepts any parameter passed to GFG(double[]), so GFG(Object) is less specific. (Every double array is an Object, but not every Object is a double array.)

This article is contributed by Shubham Juneja. If you like Lazyroar and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments