Search code examples
javaobjectinstance

How can I get a value of instance which is already set in another class?


I'm a new to Java. I have 3 classes: 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. Can you help me to realize that I can get the value of instance which I have set in another 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());
    }

}


Solution

  • 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:

    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.