问题
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 :
- initialize member fields of this class.
- run the constructor of this class.
Since while executing thisString 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