-4

Java has different access levels for fields:

  • public
  • protected
  • default
  • private


Due to encapsulation concept we always trying to use private modifier with getters and setters of needed access level. It has various advantages shown in this answer. Since getters and setters are so cool, when should we prefer public/protected/default Object field; to private Object field; with public/protected/default getters and setters?

Clarification: I perfectly understand why and what are getters, setters and access modifiers. I just want comprehensive answer for a certain question above.

Russiancold
  • 1,179
  • 1
  • 11
  • 26
  • How to edit my question? I didn't find the answer. I know the differences between public and private. But I want some examples when public, protected, default field is better then private plus get and set. – Russiancold Mar 14 '17 at 07:33

1 Answers1

0

We can achieve complete encapsulation in java by making members of a class private and access them outside the class only through getters and setters. Although a lesser degree of encapsulation can be achieved by making the members public or protected.

John Joe
  • 12,412
  • 16
  • 70
  • 135
Chetan Joshi
  • 5,582
  • 4
  • 30
  • 43