0

An instance a of class A has an instance b of class B.

How can b access a variable of a?

class A {
    boolean flag;
    B b;

    public static void main(String[] args) {
        A a = new A();
    }

    public A() {
        b = new B();
        b.doSomething();
        chageFlag();
        b.doSomething();
    }

    void changeFlag() {
        // do something with flag
    }
    // other stuff
}

class B {
    void doSomething() {
        // here I need to access a from the instance owning b.
        boolean aFlag = ?? // how to access a.flag ??
    }
}
Raf
  • 1,628
  • 3
  • 21
  • 40

2 Answers2

1

You will not be able to access a variable of A in this instance because A and B have no parent/ child or outer/inner class relationship here.

The way to do this is to pass the instance of A to B, such as,

B b = new B(this);

For this you need to adjust the constructor to take in A as a parameter.

Sachinwick
  • 92
  • 1
  • 7
0

As your code is, b has no way of reaching a; simply because it does not have a reference to it.

If the two classes are so related that you need b to know about a, then you can make B an inner class in A:

class A {
    boolean flag;
    B b;

    public static void main(String[] args) {
        A a = new A();
    }

    public A() {
        b = this.new B();
        b.doSomething();
        changeFlag();
        b.doSomething();
    }

    void changeFlag() {
    }

    class B {
        void doSomething() {
            boolean aFlag = flag;
        }
    }
}

B.doSomething() is able to read flag from the enclosing class because B is an inner class.

Be aware that this solution is not appropriate in all situations, it makes the coupling between the two classes even tighter.

ernest_k
  • 44,416
  • 5
  • 53
  • 99