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

后端 未结 17 1559
抹茶落季
抹茶落季 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:35

    The mentioned keywords are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.

    private - Only the current class will have access to the field or method.

    protected - Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.

    public - Any class can refer to the field or call the method.

提交回复
热议问题