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

标签 java class

我有两个这样的类(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接受在其构造函数中实现某个接口(interface)的类的实例,并具有 A实现该接口(interface)。

你的选择取决于你。我按照大致递减的耦合顺序给出了它们,其中耦合越松散越好(通常)。

代码中的第三个选项:

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 .

关于java - 如何从我在该类中创建的类访问该类的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14932662/

相关文章:

java - j2me网络

javascript - 将 'Const' ReactJs 组件转换为基于参数的类

java - 包含来自 xml 的其他数据集

将指针转换为 cython 中类的实例

python - 如何在 Python 中编写有效的类装饰器?

Python 类不会执行我的函数

c# - 为什么在面向对象设计中某些模式的类具有单独的数据类

java - Spring Boot 1.4 : Spring Data Cassandra 1. 4.2 与 Cassandra 3.0 不兼容?

java - 如何在 Jetty 9.4 中使用 Spring WebApplicationInitializer?

java - 莫里斯图表从外部 JSON 中破坏