Write a Java program to Accessing Superclass Members


This Java program demonstrates the use of the super keyword to access a member of the parent class from a subclass. In this program, there are two classes: Parent (the parent class) and Child (the child class). The Child class extends the Parent class and accesses a protected member from the parent class using the super keyword. Here's an explanation of the program:

  • public class SuperClassMember: This is the main class that contains the main method, the entry point of the program.
  • public static void main(String[] args): The main method is where the program execution starts. It creates an object of the Child class and calls the displayMessage method to demonstrate accessing the msg member from the parent class.
  • Child child = new Child();: This line creates an object of the Child class.
  • child.displayMessage();: This line calls the displayMessage method on the child object, which accesses the msg member from the parent class using the super keyword.
  • class Parent: This is the parent class, which has a protected member named msg initialized to "Hello World."
  • class Child extends Parent: This is the child class that extends the Parent class, inheriting the msg member.
  • void displayMessage(): The Child class defines a method named displayMessage. Inside this method, it uses the super keyword to access the msg member from the parent class.

This program demonstrates how to use the super keyword to access a member of the parent class from the child class. In this case, the Child class accesses the protected msg member from the Parent class and prints its value to the console. The super keyword is used to explicitly refer to the parent class's member, allowing you to access and use it in the child class.


Source Code

public class SuperClassMember	// Main class
{
	public static void main(String[] args)
	{
		Child child = new Child();
		child.displayMessage();
	}
}
 
class Parent  // Parent class
{
	protected String msg = "Hello World";
}
 
class Child extends Parent	// Child class
{
	void displayMessage()
	{
		System.out.println(super.msg); // Accessing parent class member using super keyword
	}
}

Output

Hello World