我得到了 NullPointerException [英] I got NullPointerException

查看:58
本文介绍了我得到了 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将回到 Java 中的 OOP.在这里,我遇到了一个简单示例的问题:

I'm going back to OOP in java. Here I got problem with simple example:

class CreateString {
    private String name;

    public CreateString(String name) {
        this.name = name;
    }

    String string = new String(name);//AAA
}

public class Main {

    public static void main(String[] args) {
        CreateString myName = new CreateString("tomjas");
    }
}

我从表示为AAA"的行中得到 NullPointerException.当我将第二行更改为

I got NullPointerException from line denoted as "AAA". When I change the second line into

 private String name="";

没关系.那个代码有什么问题?我认为该字段已初始化为可以从构造函数得出的结论.任何提示和指向文档的指针?

it's ok. What is wrong with that code? I thought that field is initialised as one could conclude from constructor. Any hints and pointers to documentation?

推荐答案

你的 string 变量是一个类属性.因此,它会在您的类实例创建时被初始化.但当时 name 仍然为 null,因为您只在构造函数中为 name 赋值.所以你最终得到一个 NullPointerException.

Your string variable is a class attribute. Therefore it will be initialized when your class instance is created. But at that time name is still null, as you only assign a value to name in the constructor. So you end up with a NullPointerException.

要修复它,将 string = new String(name); 移动到构造函数中:

To fix it, move string = new String(name); into the constructor:

class CreateString {
  private String name = null;
  private String string = null;

  public CreateString(String name) {
      this.name = name;
      string = new String(name);
  }
}

由于构造函数仅在所有属性都初始化后才执行,因此将行 private String string; 放在哪里并不重要.您也可以将它放在构造函数之后(就像您所做的那样),它仍然可以.

As the constructor is only executed after all the attributes have been initialized, it doesn't matter where you put the line private String string;. You could also place it after the constructor (as you did), and it would still be fine.

这篇关于我得到了 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆