43

I don't understand the difference between protected and private members or methods, as I assumed both will hide the member or the function to access from outside the class.

What is the difference between the protected and the private keywords?

Cody Gray
  • 230,875
  • 49
  • 477
  • 553
danijar
  • 30,040
  • 39
  • 151
  • 272

5 Answers5

82

private - only available to be accessed within the class that defines them.

protected - accessible in the class that defines them and in other classes which inherit from that class.

dsgriffin
  • 64,660
  • 17
  • 133
  • 135
14

Things that are private are only visible within the class itself.

Things that are protected are visible in the class itself and in subclasses.

Jesper
  • 195,030
  • 44
  • 313
  • 345
8

The difference is who can access those functions.

  • Private = only members of the same class can access the function.

  • Protected = Same as private but derived classes can also access.

akrabi
  • 4,144
  • 2
  • 16
  • 19
6

Private members can only be used by that classes members and its friends; protected members can be inherited by other classes, and can be used by the classes members and friends.

b3h3m0th
  • 1,270
  • 1
  • 11
  • 22
5

Private methods are usually visible to class instances (internal implementations), protected methods are visible to subclasses and classes in the same package (inheritance and restricted usage).

Fabio
  • 71
  • 5