我们可以在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()$ c相同$ C>。因此,在运行时抛出没有
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屋!