What is the difference between public, private, and protected?

后端 未结 17 1549
抹茶落季
抹茶落季 2020-11-21 07:54

When and why should I use public, private, and protected functions and variables inside a class? What is the difference between them?<

17条回答
  •  有刺的猬
    2020-11-21 08:34

    Visibility Scopes with Abstract Examples :: Makes easy Understanding

    This visibility of a property or method is defined by pre-fixing declaration of one of three keyword (Public, protected and private)

    Public : If a property or method is defined as public, it means it can be both access and manipulated by anything that can refer to object.

    • Abstract eg. Think public visibility scope as "public picnic" that anybody can come to.

    Protected : when a property or method visibility is set to protected members can only be access within the class itself and by inherited & inheriting classes. (Inherited:- a class can have all the properties and methods of another class).

    • Think as a protected visibility scope as "Company picnic" where company members and their family members are allowed not the public. It's the most common scope restriction.

    Private : When a property or method visibility is set to private, only the class that has the private members can access those methods and properties(Internally within the class), despite of whatever class relation there maybe.

    • with picnic analogy think as a "company picnic where only the company members are allowed" in the picnic. not family neither general public are allowed.

提交回复
热议问题