Java对象未初始化,可以调用对象类的静态方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenbetter1996/article/details/88296247
package xyz.cglzwz.question_bank.simple;

public class StaticTest {
	public static void sayHi() {
		System.out.println("hi");
	}
	
	public void sayBye() {
		System.out.println("bye");
	}
	
	public static void main(String[] args) {
		StaticTest t = null;
		t.sayHi();   // 可以正常输出
		t.sayBye();  // 编译通过,运行抛出空指针
	}

}

控制台结果:

hi
Exception in thread "main" java.lang.NullPointerException
	at xyz.cglzwz.question_bank.simple.StaticTest.main(StaticTest.java:15)

空指针是指栈中的引用指向堆中的对象为空。
但是static方法在静态区,根本没有指针,和对象无关。但是引用依然可以调用。

猜你喜欢

转载自blog.csdn.net/chenbetter1996/article/details/88296247