×

Java Programs

Java Practice

Java program to demonstrate the protected access specifier

Write a Java program to demonstrate the example protected access specifier.
Submitted by Nidhi, on March 24, 2022

Problem statement

In this program, we will 4 classes A, B, C, and Main. Classes A, B, C contains a method with a protected specifier. Here, we will implement multi-level inheritance in A, B, C classes.

Java - Protected access specifier

The protected member of a class can be accessed:

  1. Within the same class.
  2. Derived classes of same packages.
  3. Different classes of the same packages.
  4. Derived classes of different packages.

Java program to demonstrate the protected access specifier

The source code to demonstrate the protected access specifier is given below. The given program is compiled and executed successfully.

// Java program to demonstrate the 
// protected access specifier

class A {
  protected void MethodA() {
    System.out.println("MethodA called");
  }
}

class B extends A {
  protected void MethodB() {
    System.out.println("MethodB called");
  }
}

class C extends B {
  protected void MethodC() {
    System.out.println("MethodC called");
  }
}

public class Main {
  public static void main(String[] args) {
    C obj = new C();

    obj.MethodA();
    obj.MethodB();
    obj.MethodC();
  }
}

Output

MethodA called
MethodB called
MethodC called

Explanation

In the above program, we created 4 classes A, B, C, and Main(). Here, we implemented multi-level inheritance and created methods using protected access specifiers.

The Main class contains a method main(). The main() method is the entry point for the program, here we created the object of class C and called methods of all inherited classes, and printed the messages.

Java Inheritance Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.