Search code examples
javagetter-setter

How to set Setters from main and get the Getters from Another Class Java 7


I have 3 classes; 1) Main 2) SettersAndGetters 3) AnotherClass. In my main class, I set the setters. And I am looking for a way to access these values from AnotherClass. Right now I am getting a null which is due to the new instance I created. So how can I get round that, how to retrieve the value that I set in main.

public class Main{

   public static void main(String args[]){
      GettersAndSetters sg = new GettersAndSetters();
      AnotherClass copyOfSG = new AnotherClass();

      sg.setName("Mo");
      sg.setAge(20);
      sg.setIdNum("77777");

      System.out.print("Name : " + sg.getName() + " Age : " + sg.getAge()+"\n");
      System.out.println(copyOfSG.printout());
      //In here I am trying to print the value that is 
      //in my 3rd class "AnotherClass" but i am getting null. 

   }
}

Output:

Name : Mo Age : 20
Age: 0
Name: null

SettersAndGetters:

public class GettersAndSetters{
   private String name;
   private String idNum;
   private int age;
   public int getAge(){
      return age;
   }
   public String getName(){
      return name;
   }

   public String getIdNum(){
      return idNum;
   }

   public void setAge( int newAge){

      age = newAge;
   }

   public void setName(String newName){
      name = newName;
   }

   public void setIdNum( String newId){
      idNum = newId;
   }
}

AnotherClass:

public class AnotherClass {

    public void printout() {
        GettersAndSetters gs1 = new GettersAndSetters();

        System.out.println("Age: " + gs1.getAge());
        System.out.println("Name: " + gs1.getName());

        System.out.println();

    }

}

Solution

  • This occurs because you created two independent instances of GettersAndSetters in Main and in AnotherClass. Look:

       public static void main(String args[]){
    
          GettersAndSetters sg = new GettersAndSetters(); //first instance
          AnotherClass copyOfSG = new AnotherClass();
    
          ...
       }
    

    public class AnotherClass {
    
        public void printout() {
            GettersAndSetters gs1 = new GettersAndSetters(); //second instance
            ...
        }
    }
    

    And you're setting properties in first instance, but attempting to read it from second. To solve just pass first instance from Main to method in AnotherClass as suggested by Satya.

    public class AnotherClass {
    
        public void printout(GettersAndSetters sg) {
            System.out.println("Age: " + sg.getAge());
            System.out.println("Name: " + sg.getName());        
            ...
        }
    }
    

    and call it next way:

    public class Main{
    
       public static void main(String args[]){
          GettersAndSetters sg = new GettersAndSetters();
          AnotherClass copyOfSG = new AnotherClass();
    
          ...
    
          copyOfSG.printout(sg);
       }
    }