Can we declare a top level class as protected or private in Java?


No, we cannot declare a top-level class as private or protected. It can be either public or default (no modifier). If it does not have a modifier, it is supposed to have a default access.

Syntax

// A top level class
   public class TopLevelClassTest {
      // Class body
}
  • If a top-level class is declared as private the compiler will complain that the modifier private is not allowed here. This means that a top-level class cannot be a private, the same can be applied to protected access specifier also.
  • Protected means that the member can be accessed by any class in the same package and by subclasses even if they are in another package.
  • The top-level classes can only have public, abstract and final modifiers, and it is also possible to not define any class modifiers at all. This is called default/package accessibility.
  • We can declare the inner classes as private or protected, but it is not allowed in outer classes.
  • More than one top-level class can be defined in a Java source file, but there can be at most one public top-level class declaration. The file name must match the name of the public class.


Declare the class as Protected

Example

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");
   }
}

In the above example, we can declare the class as protected, it will throw an error says that modifier protected not allowed here. So the above code doesn't execute.

Output

modifier protected not allowed here


Declare the class as Private

Example

Live Demo

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, it will throw an error says that modifier private not allowed here. So the above code doesn't execute.

Output

modifier private not allowed here

Updated on: 30-Jul-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements