Java – how can I call a method of a null object?
•
Java
public class JavaPuzzler {
public class JavaPuzzler { public static void main(String[] args) { JavaPuzzler javaPuzzler = null; System.out.println(javaPuzzler.get()); } private static String get(){ return "i am a java puzzler"; } }
You might think it should throw a NullPointerException because the get () method of the initialized local variable called by the main method is null, and you cannot call the method on null
But if you run this program, you will see it print "I am a Java puzzle"
Can someone give me an answer? Thank you in advance
Solution
In the code example, get () is a static member of the class, not an instance You do not need an instance to call this method
public static String get() // belongs globally to class,no instance required public String get() // belongs to instance
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码