Since static methods can be called directly from the class (i.e. ClassName.methodName), why it is required to call a static method with the object of the class?
If someone knows then, elaborate with example.
public static void methodA(){
}
Since static methods can be called directly from the class (i.e. ClassName.methodName), why it is required to call a static method with the object of the class?
If someone knows then, elaborate with example.
public static void methodA(){
}
Yes,and this is a strange situation. Below is the example.
Output: foo
Explanation : it is expected this should throw a null pointer exception but it just gives you a warning that "The static method foo() from the type Test should be accessed in a static way". But when executing it will work.
Very well you can call a static method with null object.
See the example below.
Above code snippet will print hello
Because at the compile time
h.hash()
will be converted toHashing.hash()
sincehash()
is a static method.When I de-compiled
.class
file I got this code.As you can see in the above snippet
h.Hash();
is converted toHashing.Hash();
HTH!!
The following code contains an example, in which a static method is called via a
null
reference.Because
Test::greeting
is a static method, the expressiontest.greeting()
is identical toTest.greeting()
. For that reason, there is noNullPointerException
thrown at runtime.There is no need for an instance while invoking static member or method.
Since static members belongs to class rather than instance.
Example 15.11.1-2. Receiver Variable Is Irrelevant For static Field Access
The example from spec it self.
And the analysis of why it is happening