I am trying to make a project with packages of classes with different access modifiers to see all the characteristics of classes with different access modifiers. I tried having a package with a public class, one with a default class and then tried to have 2 other for protected and private classes but it said “Illegal modifier for the class privatez; only public, abstract & final are permitted” for them. Why is this so. And secondly, is testing stuff for each class a good way to understand it. I am trying to give a better question than the previous post. I also want to learn application of each access modifier.
Share
The simple answer is that the JLS says you can’t declare a top-level class as
private.The reason is that it doesn’t make sense to have a class that is only visible to itself. There’s no way that any other class would ever be able to use it (apart, hypothetically, from using dirty tricks with reflection). So the JLS is just saying: “It doesn’t make sense, and I’m not allowing it.”
(Now a nested class can have access
private… but that’s because theprivatemeansprivateto all classes in the outermost enclosing classes …)I think it is better to read and try to understand the text book / tutorial. The problem is that if you try to learn by writing your own examples, you can easily draw the wrong conclusions from them.
For this example:
A hypothetical
protectedclass would/might only be visible to its subclasses. But classes are always visible to their subclasses, so this doesn’t make any sense. (Besides, the way to prevent subclasses is to declare a classfinal, and you can restrict subclassing using “package private”; i.e. no access modifier.)The
protectedaccess modifier only makes any sense for stuff inside a class. In a top level class, the normal meaning ofprotecteddoesn’t make any sense.(This is one of the problem of trying to learn by examples. You end up struggling with understanding why the compiler rejects the examples. Don’t expect the compiler to “explain” why something is wrong. That’s not its role.)