简体   繁体   中英

how to access the Objects initialized inside constructor(JAVA)?

I have demonstrated an example below for my questions.

class B {
    int name;

    public int getName() {
        return name;
    }

    public void setName(int name) {
        this.name = name;
    }
}

class A {

    public A() {
        // initializing object B 
        B b = new B();
    }
}

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

How I access the object of B in the Mainclass which is initialized inside the class A Constructor?

How about

class A {
  private B b;

  public A() {
    // initializing object B 
    b = new B();
  }

  public B getB () {
   return b;
  }
}

from mainClass

A a = new A();
B b = a.getB ();

One way to achieve this would be to add a getter method inside your A class which exposes the instance of B :

public class A {
    private B b;

    public A() {
        b = new B();
    }

    public B getB() {
        return b;
    }
}

Usage:

A a = new A();
B myB = a.getB();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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