Why can a class not be defined as protected?

后端 未结 12 2116
长发绾君心
长发绾君心 2020-12-04 08:03

Why can we not define a class as protected?

I know that we can\'t, but why? There should be some specific reason.

12条回答
  •  伪装坚强ぢ
    2020-12-04 08:42

    Protected is not similar to public. Protected has both package level access plus can be accessed outside of packages only by inheritance..If a class say A outside a package INHERITS a class from other package(with protected method by using INHERITANCE) it can access the methods of this class B which has protected methods but the sub-classes derived from this class i.e., A can't access the protected methods..the opposite happens with public..

    Example:

    package 2;
    class B
    {
    protected void method1()
    {
    }
    }
    package 1;
    import 2.B;
    class A extends B
    {
    //can access protected method
    }
    class C extends A
    {
    //can't access the protected method
    }
    

提交回复
热议问题