Home >Java >javaTutorial >In Java, can we declare a top-level class as protected or private?
No , we cannot declare a top-level class as private or protected. It can be public or default ( no modifiers ). If there are no modifiers, there should be default access.
// A top level class public class TopLevelClassTest { // Class body }If you declare a top-level class as private, the compiler will report an error and prompt "The modifier private is not allowed here." This means that top-level classes cannot be private, and the same applies to the protected access modifier. Protected means that the member can be accessed by any class in the same package as well as subclasses, even if they are in another package. Top-level classes can only have public, abstract, and final modifiers, or they may not define any class modifiers. This is called default/package access. We can declare inner class as private or protected but this is not allowed in outer class classes.
Live Demo
protected class ProtectedClassTest { int i = 10; void show() { System.out.println("Declare top-level class as protected"); } } public class Test { public static void main(String args[]) { ProtectedClassTest pc = new ProtectedClassTest(); System.out.println(pc.i); pc.show(); System.out.println("Main class declaration as public"); } }
Above In the example, we can declare the class as protected, and it will throw an error , indicating that the modifier protected is not allowed to be used here . Therefore, the above code will not execute.
modifier protected not allowed here
Live demonstration
private class PrivateClassTest { int x = 20; void show() { System.out.println("Declare top-level class as private"); } } public class Test { public static void main(String args[]) { PrivateClassTest pc = new PrivateClassTest(); System.out.println(pc.x); pc.show(); System.out.println("Main class declaration as public"); } }
In the above example, we can declare the class as private and it will throw an error indicating that the modifier private is not allowed here . So the above code will not execute.
modifier private not allowed here
The above is the detailed content of In Java, can we declare a top-level class as protected or private?. For more information, please follow other related articles on the PHP Chinese website!