0

I have three java class ( A.java & B.java & C.java ) that all of them located in a common package . I want to make an object of class B ( instanceOfB ) in class A and could use that object in class C . How do that ? Thanks

public class A{
   public B instanceOfB;
}

public class B{ 
}

public class C{ 
}

2 Answers2

1

You could have a getter method to retrieve the instance of class B from the A object and use it in C:

public B getB() {
   return this.B;
}
Vladimir Stanciu
  • 1,468
  • 1
  • 7
  • 24
0

Somehow you need to pass the instance of B to C during construction. The simplest way is to have a constructor on C:

public class C {
  private B myInstanceOfB;
 
  public C(B instance) {
    this.myInstanceOfB = instance;
  }
}

Now this would mean that whoever creates a C instance must know to do that and have access to a B instance. It's possible that you want to "hide" that requirement, then you can do things like add a factory method for C into the A class:

public class A {
  private B instanceOfB;

  public C createC() {
    return new C(instanceOfB);
  }
}

If you do this you can also make the C constructor package-private to indicate to potential users that they should not attempt to instantiate it directly (and document in the JavaDoc how to get a C instance).

Whether or not that makes sense depends on what the relation between A and C is.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614