Q:

Java program to demonstrate the protected access specifier

belongs to collection: Java Inheritance Programs

0

Java program to demonstrate the protected access specifier

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

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

Output:

MethodA called
MethodB called
MethodC called

Explanation:

In the above program, we created 4 classes ABC, 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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

java programming polymorphism simple example | Ani... >>
<< Java program to override a base class method into ...