Why Protected access modifier used in Java?

Java 8Object Oriented ProgrammingProgramming

The data members and methods of a class can be accessed from the same package or sub-classes in a different package if they are specified with the protected access modifier. The keyword protected is used to specify this modifier.

A program that demonstrates the protected access modifier in Java is given as follows:

Example

 Live Demo

class A {
   protected int a = 9;
   public void printA() {
      System.out.println("Value of a = " + a);
   }
}
public class Demo {
   public static void main(String args[]) {
      A obj = new A();
      obj.a = 18;
      obj.printA();
   }
}

Output

Value of a = 18

Now let us understand the above program.

The class A has a protected data member a that can be accessed from the same package or sub-classes in a different package. The public method printA() displays the value of a. A code snippet which demonstrates this is as follows:

class A {
   protected int a = 9;
   public void printA() {
      System.out.println("Value of a = " + a);
   }
}

In the main() method in class Demo, an object obj of class A is created. The value of obj.a is modified which is possible as it is protected and the modification is done in the same package. Then printA() method is called. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String args[]) {
      A obj = new A();
      obj.a = 18;
      obj.printA();
   }
}
raja
Published on 15-Feb-2019 10:02:38
Advertisements