ADVERTISEMENT
ADVERTISEMENT

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 Solution:

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 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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.