Write a Java program to demonstrates the use of the protected access specifier


This Java program demonstrates the use of the protected access modifier and inheritance. In this program, there are two classes, Person (the parent class) and Student (the child class). The Student class inherits from the Person class and is able to access the protected method defined in the parent class. Here's an explanation of the program:

  • class Student extends Person: This is the Student class, which inherits from the Person class. In this class, there is a method showDetails().
  • void showDetails(): The showDetails method in the Student class calls the displayDetails() method, which is protected and defined in the parent class Person.
  • public static void main(String[] args) : This is the main method, the entry point of the program.
  • Student student = new Student();: It creates an instance of the Student class.
  • student.showDetails();: This line calls the showDetails method on the student object, which, in turn, calls the displayDetails method from the parent class.
  • class Person: This is the parent class, which contains a protected method named displayDetails.
  • protected void displayDetails(): The displayDetails method in the Person class is marked as protected. This means it is accessible within the class, by derived classes (such as Student), and by other classes in the same package.

In this program, the Student class inherits the displayDetails method from the Person class. Despite being marked as protected, it is accessible within the Student class, allowing the showDetails method to call it. When the showDetails method is invoked, it correctly prints "This is a person" to the console, showing that the protected method can be accessed within the derived class


Source Code

class Student extends Person
{
	void showDetails()
	{
		displayDetails(); // Protected method is accessible in the derived class
	}
 
	public static void main(String[] args)
	{
		Student student = new Student();
		student.showDetails();
	}
}
 
class Person
{
	protected void displayDetails()
	{
		System.out.println("This is a person");
	}
}

Output

This is a person