Java调用子类child.any()抛出NullPointerException的原因及解决方案
NullPointerException 问题原因
你代码中创建了parent、child两个完全独立的对象实例,二者的成员变量互不干扰:你仅对parent对象的tmp成员完成了赋值,child对象继承自父类的tmp成员从未被赋值,默认值为null,调用child.any()时执行tmp.printTmp()就会触发空指针异常。
另外你提供的代码本身存在基础语法问题,无法直接编译:
- 所有类定义缺少
class关键字,比如public main应改为public class Main - 入口主方法缺少
static修饰符
修复方案
- 方案1(最常用):直接给
child对象的tmp成员赋值,替换掉对无关parent对象的赋值操作
修改主方法中的对应代码即可:
public class Main { public static void main(String[] args) { Child child = new Child(); Tmp tmp = new Tmp(); child.setter(tmp); child.any(); } }
- 方案2(适合多实例共享场景):将
Parent类的tmp成员改为静态变量,所有父类、子类实例共用同一个tmp值
public class Parent { static Tmp tmp; protected void setter (Tmp tmp) { this.tmp = tmp; } }
- 方案3(适合强制初始化场景):给父类新增带参数的构造方法,子类实例化时必须传入
tmp完成初始化,避免出现空值
public class Parent { Tmp tmp; // 新增带参数构造 public Parent(Tmp tmp) { this.tmp = tmp; } protected void setter (Tmp tmp) { this.tmp = tmp; } } public class Child extends Parent { // 子类构造调用父类带参构造完成初始化 public Child(Tmp tmp) { super(tmp); } protected void any() { tmp.printTmp(); } } // 主方法实例化Child时直接传入tmp public static void main(String[] args) { Tmp tmp = new Tmp(); Child child = new Child(tmp); child.any(); }
内容的提问来源于stack exchange,提问作者Blue Fire
相关产品推荐
相关产品推荐

