Search code examples
javaclassinheritanceprotectedaccess-specifier

Child Class cannot be protected


import java.util.*;

public class NewTreeSet2{
    void count(){
        for (int x=0; x<7; x++,x++){
            System.out.print(" " + x);
        }
    }
}
protected class NewTreeSet extends NewTreeSet2{
    public static void main(String [] args){
        NewTreeSet2 t = new NewTreeSet2();
        t.count();
    }
}

Here, I cannot make the NewTreeSet sub class as protected. Why is this? I am not trying to accomplish anything, this is only for my understanding of the access specifiers.


Solution

  • public is the only access-modifier that can explicitly be applied to a top level class in Java. The protected modifier in case of a class can only be applied to inner classes.

    Section 8.1.1 of the Java language specification says this :

    The access modifiers protected and private pertain only to member classes within a directly enclosing class declaration

    So why can't top level classes be marked as protected? The purpose of protected access modifier in Java is to add restrictions on the access to a member of a class. Since a top level class is not a member of any class, the protected access modifier does not make sense for top level classes. Inner classes can be marked as protected because they are indeed members of a class. The same rules apply for private as well.