45

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 - on strike
  • 239,200
  • 50
  • 490
  • 574
danijar
  • 32,406
  • 45
  • 166
  • 297

5 Answers5

86

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
  • 66,495
  • 17
  • 137
  • 137
15

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
  • 202,709
  • 46
  • 318
  • 350
9

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,244
  • 2
  • 18
  • 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,330
  • 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