我一直在互联网上搜索在一个类中创建一个对象的实例,并在另一个类中使用相同的实例。我没有发现任何适用于我想做的帖子。这是我想要做的一个例子。
public class ThisClass{
public ThisClass{
//This is the object I want to create
}
}
public class FirstClass{
public ThisClass thisclass = new ThisClass();
}
public class SecondClass{
//Now in SecondClass I want to be able to access the instance of ThisClass
//I created in FirstClass
}
关于在这里做什么的任何想法都不会太复杂,让代码成为一个噩梦?
答案 0 :(得分:0)
我想到了三个解决方案:
ThisClass
单身 - 这样您就永远无法实例化多个ThisClass
类的类。ThisClass
类型的实例,并将其通过构造函数传递给所有其他类。ThisClass
的静态实例变量,然后在想要具有相同ThisClass
的类中扩展/实现此抽象类/接口。 1}}实例。答案 1 :(得分:0)
以这种方式:
public class ThisClass {
public ThisClass() {
// This is the object I want to create
}
}
public class FirstClass {
private ThisClass thisClass = new ThisClass();
public ThisClass getThisClass() {
return thisClass;
}
}
public class SecondClass {
//Now in SecondClass I want to be able to access the instance of ThisClass
//I created in FirstClass
private ThisClass thisClass;
public SecondClass(ThisClass thisClass) {
this.thisClass = thisClass;
}
}
public class ThirdClass {
public ThirdClass() {
new SecondClass(new FirstClass().getThisClass());
}
}