Search code examples
javaobjectmethodsgetter-setter

Loading an Object with getter and setter


I'm new in Java Objects and my question is:

  • I have the class Person
  • I am creating a new Object person5
  • I'm setting the ID to 5
  • Now I want that in my Object person5 are all information the person with the ID 5 has, are in the object person5
  • Then i want to get the age of the person5

When I debugged my code only the ID was set to 5 all other variables were null.

Person person5 = new Person();
person5.setID(5);
person5.getAge();


@Id @Column(name = "ID") 
private Integer id; 

@Column(name = "AGE") 
private Integer age; 

public Integer getId() { 
return id; 
} 

public void setId(Integer id) { 
this.id = id; 
} 

public Integer getAge() { 
return age; 
} 

public void setAge(Integer age) { 
this.age = age; 
}

What am I doing wrong? Can somebody help me?


Solution

  • Person person5 = new Person();
    

    You created a new Person

    person5.setID(5);
    

    You decided that the ID of the newly created person will be 5.

    person5.getAge();
    

    Since you haven't explicitly told Java to change the age of the person from what was set by the constructor, it will tell you what it was told, which is nothing.

    Now I want that in my Object person5 are all information the person with the ID 5 has, is in the object person5

    At this point, Java knows nothing about which person5 you are talking about. If you want it to have all the attributes of a similar person, you'll have to tell Java to either set all those attributes into your object or create a new one using values (from DB presumably).

    It is better to clear up doubts on OOPS before getting into deeper concepts like DB connectivity.