I was recently asked what is the output of the next code:
class MyClass {
static void printMessage() {
System.out.println("Hello from static");
}
public static void main(String[] args) {
MyClass instance = null;
instance.printMessage();
}
}
Output
"Hello from static" without compile or runtime errors.
I know that static methods can be called using the name of the class such as MyClass.staticMethod() and also I know that you can call a static method inside a non-static one but the code above is confusing for me. Can anyone explain to me how is possible to call a static method using a null instance? Thanks.