Thursday, 14 September 2017

Statics in Java

This one comes straight out of the Java Language Specification1, paragraph 15.12.4.1:
class Test1 { 
    static void mountain() 
    { 
        System.out.println("Monadnock"); 
    } 

    static Test1 favorite()
    { 
        System.out.print("Mount "); 
        return null
    } 

    public static void main(String[] args) 
    { 
        favorite().mountain(); 
    } 
}
What is the output of this program?

References

[1] The Java Language Specification, Java SE 8 Edition
https://docs.oracle.com/javase/specs/

Wednesday, 6 September 2017

Method Overloading in Java - Answer

The output of the program in Method Overloading in Java:
/opt/tools/java/jdk1.8.0_60/bin/java com.mrbear.App
Hello World!
Brian Goetz
Object
Object
So, from the tutorials1:
Note: Overloaded methods should be used sparingly, as they can make code much less readable.
Quoting2 from the JLS3:
When a method is invoked (§15.12), the name of the class, the name of the method, the number of actual arguments and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2).

References

[1] Oracle The Java™ Tutorials - Defining Methods
https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html
[2] StackOverflow - Overloaded method selection based on the parameters real type
https://stackoverflow.com/questions/1572322/overloaded-method-selection-based-on-the-parameters-real-type
[3] The Java Language Specification, Java SE 8 Edition
https://docs.oracle.com/javase/specs/jls/se8/jls8.pdf