英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论