Java protected access specifier



Protected Access Specifier

Consider the following example –

package com.c4learn.inheritance;

public class ProtectedExample {

   public void publicMethod(){
   }

   private void privateMethod(){
   }
	
   protected void protectedMethod(){
   }

   public static void main(String[] args) {
       ChildClass c1 = new ChildClass();
       c1.testMethods();
   }
}

class ChildClass extends ProtectedExample {
	
   public void testMethods() {
      publicMethod();
      protectedMethod();
      privateMethod();  //Error
   }
}

Output :

Compile Time Error

Explanation :

  1. From subclass we cannot access the private members of the superclass.
  2. subclass you can access its superclass’s public and protected methods and fields
  3. If the subclass and the superclass are in the same package, you can also access the superclass’s default methods and fields