Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "this" and"super" keywords in Java

Tags:

java

keyword

What is the difference between the keywords this and super?

Both are used to access constructors of class right? Can any of you explain?

like image 474
Sumithra Avatar asked Oct 26 '10 11:10

Sumithra


People also ask

What is the difference between this and super keyword?

this keyword mainly represents the current instance of a class. On other hand super keyword represents the current instance of a parent class. this keyword used to call default constructor of the same class. super keyword used to call default constructor of the parent class.

What is the difference between this () and super () in Java?

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. When invoking a superclass version of an overridden method the super keyword is used.

Is super and this same?

super refers to the base class that the current class extends. this refers to the current class instance.

What is difference between this and this () in Java?

In Java, both this and this() are completely different from each other. this keyword is used to refer to the current object, i.e. through which the method is called. this() is used to call one constructor from the other of the same class.


2 Answers

Lets consider this situation

class Animal {   void eat() {     System.out.println("animal : eat");   } }  class Dog extends Animal {   void eat() {     System.out.println("dog : eat");   }   void anotherEat() {     super.eat();   } }  public class Test {   public static void main(String[] args) {     Animal a = new Animal();     a.eat();     Dog d = new Dog();     d.eat();     d.anotherEat();   } } 

The output is going to be

animal : eat dog : eat animal : eat 

The third line is printing "animal:eat" because we are calling super.eat(). If we called this.eat(), it would have printed as "dog:eat".

like image 187
Nithesh Chandra Avatar answered Sep 22 '22 19:09

Nithesh Chandra


super is used to access methods of the base class while this is used to access methods of the current class.

Extending the notion, if you write super(), it refers to constructor of the base class, and if you write this(), it refers to the constructor of the very class where you are writing this code.

like image 32
Jaywalker Avatar answered Sep 23 '22 19:09

Jaywalker