-2

Providing getter and setter method for public variable is fine. It gives following advantages:

  1. Centralized control for accessing varibales
  2. Gives chance to programmer for validations before setting the value.

But for private fields if we provide getters and setters then that variable is no longer private. Doesn't it breaks encapsulation principle? Could you please explain the real advantage of using getters and setters for private members? Or is it something which we all are using blindly?

I read many blogs but could not get convincing reason for having getters and setters for private variables.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Sachin
  • 247
  • 4
  • 16
  • 26

1 Answers1

1

It's exactly the other way around. If a variable is public you can set the value without validating it. If it is private you need to access it by getters and setters and can not go around them.

Daskus
  • 929
  • 1
  • 10
  • 25