I got NullPointerException

♀尐吖头ヾ 提交于 2020-01-16 19:20:55

问题


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");
    }
}

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?


回答1:


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.

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);
  }
}

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.




回答2:


All the fields are initialised before the constructor, as such when the line initialising string runs name is still null

class CreateString {
    private String name; //<--runs first

    public CreateString(String name) { //<--runs third
        this.name = name;
    }

    String string = new String(name);//AAA <---runs second
}

You could move the string initialisation within the constructor to solve this

class CreateString {
    private String name;
    String String string;

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



回答3:


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

That line is in initializer block.So the default value is null, Since you are using it before assigning some value. Move that line to constructor.




回答4:


Since you dont have any base class defined for your class, the order of execution would be :

  1. initialize member fields of this class.
  2. run the constructor of this class.

Since while executing this
String string = new String(name);//AAA since it executes first. the variable name is still null. That's why it throws NullPointerException



来源:https://stackoverflow.com/questions/20326830/i-got-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!