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:
Output:
There are a couple of things to notice about the
private property id
and the public properties name
and age
:
lines 18 and 20
,
for private properties - line 22
.
lines 30 and 31
.
line 32
the code will not compile. Because
a private member (id
in this case) cannot be accessed/modified outside
the class body.