我有两个班级:
public class ClassA {
String NewName;
public ClassA() {
System.out.println("new name in A constructor: " + NewName);
}
public static void main(String[] args) {
ClassA aM = new ClassA();
aM.action();
aM.displayNewName();
}
public void displayNewName() {
System.out.println("new name in display method:" + getNewName());
}
public void action() {
ClassB bA = new ClassB();
System.out.println("new name in Action:" + getNewName());
}
public String getNewName() {
return NewName;
}
public void setNewName(String newN) {
NewName = newN;
System.out.println("new name in A Set Method: " + getNewName());
}
}
和
public class ClassB {
String newName = "jack";
ClassA a;
public ClassB(){
a.setNewName(newName);
}
}
我无法在jack
方法上获得ClassA
值(例如displayNewName()
和action
方法。
更新
public class ClassB {
String newName = "jack";
ClassA a = new ClassA();
public ClassB(){
a.setNewName(newName);
}
}
输出:
new name in A constructor: null
new name in A constructor: null
new name in A Set Method: jack
new name in Action:null
new name in display method:null
答案 0 :(得分:4)
变量a
未初始化。它将抛出nullpointerexception
。
你需要在构造函数中添加以下行来初始化它:a = new ClassA()
;
<强> EDIT1:强>
根据我的理解,你需要这样做:
public class ClassB {
String newName = "jack";
public ClassB(ClassA a){
a.setNewName(newName);
}
}
然后在ClassB中修改action()
public void action() {
ClassB bA = new ClassB(this);
System.out.println("new name in Action:" + getNewName());
}
答案 1 :(得分:2)
更改ClassB
public class ClassB {
String newName = "jack";
ClassA a=new ClassA(); // Initialize a
public ClassB(){
a.setNewName(newName);
}
}
编辑:
public void action() {
ClassB bA = new ClassB();
System.out.println("new name in Action:" + bA.newName);
}
答案 2 :(得分:1)
a未初始化。尝试a = new ClassA();在构造函数
中