java - 为什么类中的静态方法在其对象为空时不会给出空指针异常

标签 java static

我对为什么这段代码在理想情况下必须抛出空指针异常时起作用的概念感到惊讶

public class Test {
 public static String foo(){
 System.out.println("Test foo called");
 return "";
 }

 public static void main(String args[]){
 Test obj = null;
 System.out.println(obj.foo());
 }
}

最佳答案

当调用静态方法时,类型引用与实例相关,因此 obj.foo() 和 Test.foo() 被解析为相同的东西。

最佳实践:应静态访问静态成员

While it is possible to access static members from a class instance, it's bad form, and considered by most to be misleading because it implies to the readers of your code that there's an instance of the member per class instance.

https://sonarqube.com/coding_rules#rule_key=squid%3AS2209

建议编码如下:

public static void main(String args[]) {
 Test obj = null;
 // ....
 System.out.println(Test.foo());
 }

关于java - 为什么类中的静态方法在其对象为空时不会给出空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43789332/

相关文章:

java - 当我导入 jdl 文件时,仅生成客户端

java - sql数据与java的连接

c++ - unordered_map 静态断言失败

c++ - 将一个类的static const数据成员初始化为一个类

c - 不保留其值的静态变量

C++ : Initializing base class constant static variable with different value in derived class?

java - Java 分布式应用程序健康监视器的框架?

java - HtmlUnit ScriptException 错误

java - JTable 内容居中对齐

java - 我试图从头开始在Java中实现链表,但出现以下错误