Private class in java

Yes, we can declare a class as private but these classes can be only inner or nested classes. We can’t a top-level class as private because it would be completely useless as nothing would have access to it.

Example 1 with non inner class:

private class Main
{
	public static void main(String[] args) {
		System.out.println("Inside private class");
	}
}

Output:

Main.java:1: error: modifier private not allowed here
private class Main
        ^
1 error

Example 2 with non inner class:

private class Show{
        void display(){
            System.out.println("Inside display method.");
        }
}
public class Main
{
	public static void main(String[] args) {
		Show show = new Show();
		show.display();
	}
}

Output:

Main.java:1: error: modifier private not allowed here
private class Show{
        ^
1 error

Example with inner class:

class Display {
 
   //Private nested or inner class 
   private class InnerDisplay {
      public void display() {
         System.out.println("Private inner class method called");
      }
   }
 
   void display() {
      System.out.println("Outer class (Display) method called");
      // Access the private inner class
      InnerDisplay innerDisplay = new InnerDisplay();
      innerDisplay.display();
   }
}
 
public class Main {
 
   public static void main(String args[]) {
      // Create object of the outer class (Display)
      Display object = new Display();
 
      // method invocation
      object.display();
   }
}

Output:

Outer class (Display) method called 
Private inner class method called

Java interview questions on access modifiers

Please Share