0

In java, it is recommended to declare a variable as private and access it using a public function getVar() and set it using public function putVar().

public void setVar(int y)
{
   this.x=y;  //x is a private variable of class

}

public int getVar(){

   return this.x;
}

Why cant we just declare the variables as public and use it using object.var anywhere. In anycase, the members of the object are accessible. In one case using getVar() and in other case using object.var. Then why the get()/set() is used everywhere?

Diffy
  • 2,339
  • 3
  • 25
  • 47

0 Answers0