private String or public static String?

WereWolfBoy picture WereWolfBoy · Mar 28, 2013 · Viewed 64.5k times · Source

At my internship one of my colleagues gave me a hint. I want to know if this is good practice.

What I was doing was creating classes that are used only for the values they contain and don't have any functions that actually do something (apart from having getters, setters and a constructor). I declared my variables like this:

public class ObjectIUse{
  Private String name;

  public ObjectIUse(String name){
    this.name = name;
  }

  public String getName(){
    return name;
  }
}

So I'm not using a setter because it should always stay the same. My colleague said that I can also do it this way:

public class ObjectIUse{
  public final String name;

  public ObjectIUse(String name){
    this.name = name;
  }
}

Because now we don't need to have any getters or setters because it is public, however it can also never be changed because it is final.

Which would be better? Or would it maybe be preferable to still make it private but also final? I mean all of the options work, obviously. I just want to know which is better and why.

Answer

MD Sayem Ahmed picture MD Sayem Ahmed · Mar 28, 2013

Make the variable private, because by doing so you'll be encapsulating the variable in your class. This has many benefits, information hiding is among one, which you'll learn if you go to the above link.

If you want it to never change after creation, then make it final too.