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 }
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!