- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between super() and this() in Java
Following are the notable differences between super() and this() methods in Java.
super() | this() | |
---|---|---|
Definition | super() - refers immediate parent class instance. | this() - refers current class instance. |
Invoke | Can be used to invoke immediate parent class method. | Can be used to invoke current class method. |
Constructor | super() acts as immediate parent class constructor and should be first line in child class constructor. | this() acts as current class constructor and can be used in parametrized constructors. |
Override | When invoking a superclass version of an overridden method the super keyword is used. | When invoking a current version of an overridden method the this keyword is used. |
Example
class Animal { String name; Animal(String name) { this.name = name; } public void move() { System.out.println("Animals can move"); } public void show() { System.out.println(name); } } class Dog extends Animal { Dog() { //Using this to call current class constructor this("Test"); } Dog(String name) { //Using super to invoke parent constructor super(name); } public void move() { // invokes the super class method super.move(); System.out.println("Dogs can walk and run"); } } public class Tester { public static void main(String args[]) { // Animal reference but Dog object Animal b = new Dog("Tiger"); b.show(); // runs the method in Dog class b.move(); } }
Output
Tiger Animals can move Dogs can walk and run
Advertisements