Yes, we can declare a class as protected but these classes can be only inner or nested classes. We can’t a top-level class as protected because declaring top class as protected will mean that it is accessible to the current package as well as sub packages. Now there’s no concept of sub packages in Java.
Example 1 with non inner class:
protected class Main { public static void main(String[] args) { System.out.println("Inside protected class"); } } |
Output:
Main.java:8: error: modifier protected not allowed here protected class Main ^ 1 error |
Example 2 with non inner class:
protected 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 protected not allowed here protected class Show{ ^ 1 error |
Example with inner class:
class Display { //Private nested or inner class protected class InnerDisplay { public void display() { System.out.println("Protected inner class method called"); } } void display() { System.out.println("Outer class (Display) method called"); // Access the protected 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 Protected inner class method called |
Java interview questions on access modifiers
- what are access modifiers in java?
- What are different types of access modifiers in java?
- What are non access modifiers in java?
- Can we use abstract and final both with a method?
- Can abstract class have final methods in java?
- Can we declare a class as private in java?
- Can we declare an abstract method as private?
- Can we declare a class as protected in java?