繁体   English   中英

如何从我在该类中创建的类中访问该类的变量?

[英]How do I access a class's variables from a class that I created within that class?

我有两个这样的类:

public class A{
    ArrayList<Runnable> classBList = new ArrayList<Runnable>();
    int x = 0;

    public A(){
        //This code here is in a loop so it gets called a variable number of times
        classBList.add(new B());
        new Thread(classBList.get(classBList.size())).start();
    }
}

public class B implements Runnable{
    public B(){

    }

    public void run(){
        //Does some things here. blah blah blah...
        x++;
    }
}

问题是我需要让类B的实例更改类A(创建类B的类)中的变量x。但是,我不知道如何让类B知道它需要更改值,或者它可以。 任何有关如何更改它的建议将不胜感激。 谢谢!

您需要授予B实例访问A实例的权限。 有两种方法可以做到这一点:

  1. B从派生A ,让(他们或存取)的数据字段protectedA 我倾向于回避这一点。

  2. 使B在其构造函数中接受A实例。

  3. 使B接受在其构造函数中实现某些接口的类的实例,并让A实现该接口。

选择哪种取决于您。 我给它们的耦合顺序大致是递减的,耦合越松散,越好(通常)。

代码中的第三个选项:

public TheInterface {
    void changeState();
}

public class A implements TheInterface {
    ArrayList<Runnable> classBList = new ArrayList<Runnable>();
    int x = 0;

    public A(){
        //This code here is in a loop so it gets called a variable number of times
        classBList.add(new B(this)); // <=== Passing in `this` so `B` instance has access to it
        new Thread(classBList.get(classBList.size())).start();
    }

    // Implement the interface
    public void changeState() {
        // ...the state change here, for instance:
        x++;
    }
}

public class B implements Runnable{
    private TheInterface thing;

    public B(TheInterface theThing){
        thing = theThing;
    }

    public void run(){
        // Change the thing's state
        thing.changeState();
    }
}

现在, AB都耦合到TheInterface ,但是只有A耦合到B B未耦合到A

您需要在B类中扩展A类,即:

public class B extends A implements Runnable {
}

这将B类设置为A类的子类,并允许其访问其变量。

您需要使B类以某种方式知道AA哪个实例创建了它。 它可以引用其创建者,例如:

public class B implements Runnable{
    private A creator;
    public B(A a){
        creator = a;
    }

    public void run(){
    //Does some things here. blah blah blah...
    x++;
    }
}

然后从类A传递创建者时将其传递给创建者:

...
classBList.add(new B(this));
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM