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 Solution:

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.

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.

Program/Source Code:

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();



MethodA called
MethodB called
MethodC called


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!


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.