-1

我有两个班级:

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价值。ClassAdisplayNewName()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
4

3 回答 3

4

变量a未初始化。它会抛出nullpointerexception。您需要通过添加以下行在构造函数中对其进行初始化:a = new ClassA();

编辑1:

据我了解,您需要这样做:

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());
}
于 2013-08-16T12:00:49.463 回答
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);
    }
于 2013-08-16T12:06:32.033 回答
1

a 未初始化。试试 a=new ClassA(); 在构造函数中

于 2013-08-16T12:04:41.360 回答