java - 为什么这个函数调用中有 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()
解决方案
NullPointer occurs at
m_foo.print(getNumbers());
因为 m_foo 是在 getNumbers 方法中初始化的,在调用 test1 之前它永远不会被调用。
Java 按从左到右的顺序执行语句。所以首先它会检查 m_foo 对象。在 Bar 的构造函数中执行此操作的理想方法。
public Bar(){
m_foo=new Foo();
}
推荐阅读
- c - 使用 AVX 的平铺矩阵乘法
- javascript - 触发调度时,Setstate 变得混乱
- ios - RefreshControl 在其他选项卡中以类似方式使用的代码的选项卡之一中不起作用
- java - 如何使用循环取消算法解决分配问题
- c# - 多个控件上的相同 MouseMove 事件
- html-table - 获取 Tabulator js 上的最后一行索引
- java - 从 InputStream 将 tif 文件编码为 Base64
- module - nextjs 组件库
- github - 如何查看对 git repo 具有提交权限的用户列表?
- gensim - Gensim 如何在 Word2Vec 中实现子采样?