首页 > 解决方案 > 为什么这个函数调用中有 NullPointerException?

问题描述

public class Bar {

 private Foo m_foo;

 private int getNumbers(){
   m_foo=new Foo();
   return 5;
 }


 public void test1(){
   m_foo.print(getNumbers());
 }
}

public class Foo {

 public void print(int x){
   System.out.println(x);
 }
}

public class Main {
  public static void main(String args[]){
  new Bar().test1();
 }
}

NullPointerException 发生在test1()调用中,但我无法理解背后的原因。不是应该在应该首先评估m_foo的哪个中实例化吗?getNumbers()

标签: javanullpointerexception

解决方案


NullPointer occurs at

m_foo.print(getNumbers());

因为 m_foo 是在 getNumbers 方法中初始化的,在调用 test1 之前它永远不会被调用。

Java 按从左到右的顺序执行语句。所以首先它会检查 m_foo 对象。在 Bar 的构造函数中执行此操作的理想方法。

public Bar(){
    m_foo=new Foo();
 }

推荐阅读