我有两个班级:
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