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.
Program/Source Code:
The source code to demonstrate the protected access specifier is given below. The given program is compiled and executed successfully.
Output:
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.