Public And Private

Private properties and functions can be accessed or modified only in the class body.

Public members can be accessed or modified anywhere - class body, main function, other function.

It can be understood via the following code:


There are a couple of things to notice about the private property id and the public properties name and age:

  • Both public and private properties can be accessed/modified in the class body: for public properties - lines 15 and 16, for private properties - line 17.
  • Outside the Person class body (like the Main function) only public properties can be accessed/modified - lines 27 and 28.
  • If we uncomment line 29 the code will not compile. Because a private member (id in this case) cannot be accessed/modified outside the Person class body.