如何从其中一个变量

时间:2016-06-17 06:35:20

标签: java class object instance

假设我有三个班级ParentClassAClassB。 ClassA将ClassB作为其变量之一,它是Thread的扩展,包括:

父:

class Parent {
    private HashMap<ClassA, Letter> map;

    public void writeToMap(ClassA a, Letter l) {
        map.put(a, l);
    }
}

ClassA的:

class ClassA {
    private ClassB instance;
    .
    .
    .
}

然后我有了ClassB:

class ClassB extends Thread{
    //Inner variables

    public void run() {
    //do some work
    //At some point it receives an object through a Socket
    incomingLetter = (Letter) socketIn.readObject();

    //Here I need put in the Parent class' map the Letter object I just read
    //as well as the instance of ClassA that holds this one instance of ClassB
}

如何从ClassA对象中抓取实例化ClassB对象的ClassB实例,以便将其添加到地图中?这在编程方面是否可以在Java中使用?

1 个答案:

答案 0 :(得分:2)

您可以修改B类,使其包含对构造函数传递的A类的引用:

Class ClassB extends Thread {
    private ClassA classA;

    public ClassB(ClassA classA) {
        this.classA = classA;
    }

    ...
}

如果已经创建了B类,请添加方法setClassA

...
public void setClassA(ClassA classA) {
    this.classA = classA;
}