我们可以在 Java 中使用 null 对象调用静态方法吗?如果是这样,如何? [英] Can we call a static method with a null object in Java? If so, how?
问题描述
既然静态方法可以直接从类中调用(即ClassName.methodName),那为什么还需要用类的对象来调用静态方法呢?
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(){
}
推荐答案
以下代码包含一个示例,其中通过 null
引用调用静态方法.
The following code contains an example, in which a static method is called via a null
reference.
public class Test {
public static void main(String... args) {
Test test = null;
test.greeting(); // call with null reference
}
public static void greeting() {
System.out.println("Hello World");
}
}
因为Test::greeting
是一个静态方法,表达式test.greeting()
与Test.greeting()
相同.因此,在运行时不会抛出 NullPointerException
.
Because Test::greeting
is a static method, the expression test.greeting()
is identical to Test.greeting()
. For that reason, there is no NullPointerException
thrown at runtime.
这篇关于我们可以在 Java 中使用 null 对象调用静态方法吗?如果是这样,如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!