如何在Java类之间共享一个对象?

huangapple go评论78阅读模式
英文:

How to share an object between Java classes?

问题

我有三个Java类(A.java和B.java和C.java),它们都位于一个共同的包中。我想在类A中创建一个类B的对象(InstanceOfB),并且可以在类C中使用该对象。怎么做?谢谢。

public class A {
    public B instanceOfB;
}

public class B {
}

public class C {
}
英文:

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{	
}

答案1

得分: 1

你可以在A对象中添加一个获取B类实例的getter方法,并在C中使用它:

public B getB() {
   return this.B;
}
英文:

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;
}

答案2

得分: 0

Somehow 你需要在构造期间将 B 的实例传递给 C。最简单的方法是在 C 上有一个构造函数:

public class C {
  private B myInstanceOfB;

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

现在这意味着创建 C 实例的任何人都必须知道如何做,并且可以访问 B 的实例。有可能你想要“隐藏”这个要求,那么你可以在 A 类中为 C 添加一个工厂方法:

public class A {
  private B instanceOfB;

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

如果你这样做,你还可以将 C 的构造函数设置为包私有,以向潜在用户表明他们不应该尝试直接实例化它(并且在 JavaDoc 中说明如何获取 C 的实例)。

是否有意义取决于 A 和 C 之间的关系。

英文:

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.

huangapple
  • 本文由 发表于 2020年9月4日 15:41:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/63736862.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定