[英]How can I get a value of instance which is already set in another class?
I'm a new to Java.我是 Java 的新手。 I have 3 classes: 1-DataHolder 2-SetToDateHolder 3-GetFromDataHolder;我有 3 个类:1-DataHolder 2-SetToDateHolder 3-GetFromDataHolder; In the "SetToDateHolder" class, I set the value to dataholder object, and I trying to access it in the "GetFromDataHolder" class, but it got null value, I know it happens because of new instance created. In the "SetToDateHolder" class, I set the value to dataholder object, and I trying to access it in the "GetFromDataHolder" class, but it got null value, I know it happens because of new instance created. Can you help me to realize that I can get the value of instance which I have set in another class.你能帮我意识到我可以得到我在另一个 class 中设置的实例的值。
These are the classes:这些是类:
public class DataHolder {
private String myName;
public String getMyName() {
return myName;
}
public void setMyName(String myName) {
this.myName = myName;
}
}
public class SetToDataHolder {
public static void main(String[] args) {
DataHolder dataHolder = new DataHolder();
dataHolder.setMyName("Wesley");
}
}
public class GetFromDataHolder{
public static void main(String[] args) {
DataHolder dataHolder = new DataHolder();
System.out.println(dataHolder.getMyName());
}
}
I don't really understand why you need 2 additional classes as you already have the getter / setter in your DataHolder class, but here's how you should be able to proceed your logic:我真的不明白为什么你需要 2 个额外的类,因为你的 DataHolder class 中已经有了 getter / setter,但这里是你应该如何继续你的逻辑:
public class DataHolder {
private String myName;
public String getMyName() {
return myName;
}
public void setMyName(String myName) {
this.myName = myName;
}
}
public class SetToDataHolder {
private DataHolder dataHolder;
public SetToDataHolder(DataHolder dataHolder){
this.dataHolder = dataHolder;
}
public void setMyName(String myName) {
this.dataHolder.setMyName(myName);
}
}
public class GetFromDataHolder{
private DataHolder dataHolder;
public GetFromDataHolder(DataHolder dataHolder){
this.dataHolder = dataHolder;
}
public String getMyName() {
this.dataHolder.getMyName();
}
}
public class MainClass{
public static void main(String[] args){
DataHolder dataHolder = new DataHolder();
SetToDataHolder setToDataHolder = new SetToDataHolder(dataHolder);
setToDataHolder.setMyName("Wesley");
GetFromDataHolder getFromDataHolder = new GetFromDataHolder(dataHolder);
System.out.println(getFromDataHolder.getMyName());
}
}
The idea is that your SetToDataHolder and GetFromDataHolder, have access to the same instance of DataHolder.这个想法是您的 SetToDataHolder 和 GetFromDataHolder 可以访问相同的 DataHolder 实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.