gpt4 book ai didi

java - 尝试封装时获取 "Null Object Reference"

转载 作者:行者123 更新时间:2023-12-01 20:27:15 25 4
gpt4 key购买 nike

这可能非常简单,但我似乎无法弄清楚出了什么问题。我正在尝试创建一个演示来展示封装。

封装类:

public class Encapsulation {
// 'numberOfEggs' is an instance variable
// it was made 'private', because we do NOT want it to be directly accessed by other classes
// being 'private' also means that only code within the class can read or write its value
private int numberOfEggs = 10;

// getter
public int getNumberOfEggs() {
return numberOfEggs;
}

// setter
public void setNumberOfEggs(int numberOfEggs) {
if (numberOfEggs > 0) {
// we used the 'this' keyword to differentiate between the method parameter 'currentNumberOfEggs' and
// the instance variable 'currentNumberOfEggs'
this.numberOfEggs = numberOfEggs;
}
}
}

MainActivity.class:

public class MainActivity extends AppCompatActivity {

TextView defaultNumberOfEggs;
Encapsulation encapsulation;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

defaultNumberOfEggs = (TextView) findViewById(R.id.default_number_of_eggs);
defaultNumberOfEggs.setText(encapsulation.getNumberOfEggs());
}
}

activity_main.xml:

<RelativeLayout android:id="@+id/activity_main"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.vladp.studyandroid1.MainActivity">

<TextView
android:id="@+id/default_number_of_eggs"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>

启动应用程序并通过 defaultNumberOfEggs.setText(encapsulation.getNumberOfEggs()); 设置文本时,我收到“空对象引用”错误,应显示“10”(不带引号)。

最佳答案

您忘记初始化封装对象。默认情况下,它指向 null。

所以你应该在类级别定义它:

封装 encapsulation = new Encapsulation();

或者在构造函数中:

MainActivity() {
encapsulation = new Encapsulation();
}

或者在调用 super 之后的 onCreate 方法中:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
encapsulation = new Encapsulation();
setContentView(R.layout.activity_main);

....
}

关于java - 尝试封装时获取 "Null Object Reference",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43697543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com