首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在封装过程中获取“空对象引用”

在封装过程中获取“空对象引用”
EN

Stack Overflow用户
提问于 2017-04-29 15:42:49
回答 2查看 113关注 0票数 0

这可能是愚蠢的简单,但我似乎找不出是什么问题。我正在尝试创建一个展示封装的演示。

Encapsulation.class:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
<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“(没有引号)。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-04-29 15:45:26

onCreate方法中,将第一行添加为

代码语言:javascript
复制
encapsulation = new Encapsulation();
票数 1
EN

Stack Overflow用户

发布于 2017-04-29 15:55:11

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

所以,要么在类级别上定义它:

Encapsulation encapsulation = new Encapsulation();

或在构造函数中:

代码语言:javascript
复制
MainActivity() {
    encapsulation = new Encapsulation();
}

或者在调用超级后的onCreate方法中:

代码语言:javascript
复制
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    encapsulation = new Encapsulation();
    setContentView(R.layout.activity_main);

    ....
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43697543

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档