Home »
Java »
Java Programs
Java program to call the method with the same name using super keyword
Learn how to call the method with the same name using super keyword in Java?
Submitted by Nidhi, on March 23, 2022
Problem statement
In this program, we will inherit a class into another class using the "extends" keyword. Here, Superclass and subclass contain a method with the same name. Then we will use the super keyword to access the superclass method from the child class.
Java program to call the method with the same name using super keyword
The source code to call the method with the same name using the super keyword is given below. The given program is compiled and executed successfully.
// Java program to call the method with the
// same name using super keyword
class Super {
void sayHello() {
System.out.println("Super: Hello World");
}
}
class Sub extends Super {
void sayHello() {
super.sayHello();
System.out.println("Sub: Hello World");
}
}
public class Main {
public static void main(String[] args) {
Sub obj = new Sub();
obj.sayHello();
}
}
Output
Super: Hello World
Sub: Hello World
Explanation
In the above program, we created 3 classes Super, Sub, and Main. The Super and Subclass contain a method with the same name. Here, we inherited the Superclass into Sub class using the "extends" keyword. In the Sub Class constructor, we accessed the superclass method from the sub/child class using the super keyword.
The Main class contains a method main(). The main() method is the entry point for the program, here we created the object of Subclass and called the child class sayHello() method, it calls super class sayHello() method using super keyword and printed the messages.
Java Inheritance Programs »