Java Question

In Java Why is private class member directly accessible via public getter method?

class Person {

private List<String> data = new ArrayList<>();

public List<String> getData(){
return data;
}

}


Class Test {

public static void main(String args[]){

Person person = new Person();

List<String> d = person.getData();

//next two lines directly clears and adds values in the Person class private property
d.clear();
d.add("test");

}

}


This is possible because getter method returns the reference of the real object. so what`s the point of making this variable private if you can access it using getter method and store its reference.

So, what is the best practices to avoid direct access of this kind?

Neo Neo
Answer Source

Don't create a getter if you don't want one. Create methods to safely change the private member. A getter is not needed until it's needed.

Using methods to access properties means you can make checks if you need, etc.

If you do want to return the whole data object (for ease of use), but not let the caller edit it, you might return a clone.
Note: a clone won't keep up with changes made to original data. If you want that, try using an immutable list as suggested or simply use methods to get what you want.

Example:

class Person {

     private List<String> data = new ArrayList<>();

     public void clearDate () {
         data.clear();
     }

     public void addToDate (String s) {
         data.add(s);
     }

     public List<String> getData () {
         return data.clone();
     }
}

Class Test {

     public static void main(String args[]) {

         Person person = new Person();

         //next two lines safely clears and adds values in the Person class private property
         person.clearData();
         person.addToData("test");
     }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download