Q:

Java program to call the method with the same name using super keyword

belongs to collection: Java Inheritance Programs

0

Java program to call the method with the same name using super keyword

All Answers

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

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.

Program/Source Code:

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 SuperSub, 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.

 

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

total answers (1)

Java program to create an employee class by inheri... >>
<< Java program to call a superclass constructor from...