55

What is the difference between the keywords this and super?

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

informatik01
  • 16,038
  • 10
  • 74
  • 104
Sumithra
  • 6,587
  • 19
  • 51
  • 50

9 Answers9

78

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".

Nithesh Chandra
  • 1,840
  • 13
  • 12
  • 2
    I don't find this answer confusing, though you can make the last line of the output bold or add a trailing comment to emphasize that the base class was used. – razz Apr 01 '16 at 07:13
56

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.

Jaywalker
  • 3,079
  • 3
  • 28
  • 44
22

this is a reference to the object typed as the current class, and super is a reference to the object typed as its parent class.

In the constructor, this() calls a constructor defined in the current class. super() calls a constructor defined in the parent class. The constructor may be defined in any parent class, but it will refer to the one overridden closest to the current class. Calls to other constructors in this way may only be done as the first line in a constructor.

Calling methods works the same way. Calling this.method() calls a method defined in the current class where super.method() will call the same method as defined in the parent class.

Erick Robertson
  • 32,125
  • 13
  • 69
  • 98
11

From your question, I take it that you are really asking about the use of this and super in constructor chaining; e.g.

public class A extends B {
    public A(...) {
        this(...);
        ...
    }
}

versus

public class A extends B {
    public A(...) {
        super(...);
        ...
    }
}

The difference is simple:

  • The this form chains to a constructor in the current class; i.e. in the A class.

  • The super form chains to a constructor in the immediate superclass; i.e. in the B class.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
9

this refers to a reference of the current class.
super refers to the parent of the current class (which called the super keyword).

By doing this, it allows you to access methods/attributes of the current class (including its own private methods/attributes).

super allows you to access public/protected method/attributes of parent(base) class. You cannot see the parent's private method/attributes.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
  • 3
    This is answer is right if you change every occurrence of 'class' into 'object'. It is for instance not possible to call 'this' from a static method within a class. – Dave Oct 26 '10 at 13:09
  • @Dave, true...I basically went on the fact that super calls the base class (since it's a derived class of a base class). Should I say base object? If so, what's the difference between class/object? – Buhake Sindi Oct 26 '10 at 13:22
  • @TEG, I know it is a bit juggling with words and a lot of people use class and object as synonyms. The class is in fact the definition and may have static methods, constants and may even not have the possibility to be instantiated (abstract classes). An object can only exist at runtime and must be created with the ´new´ keyword. – Dave Oct 26 '10 at 13:53
  • @Dave, true, but if you look at literature, you will see words such as `base` and `derived` classes and not `based` and `derived` objects. Maybe the new literature distinguished the difference. – Buhake Sindi Oct 26 '10 at 14:05
  • @TEG, I agree on the usage of 'base' and 'derived' classes in context of a class diagram (or technical analysis) as more informal naming for superclass and subclass respectively. – Dave Oct 27 '10 at 07:43
  • @BuhakeSindi can u tell me the diagrammatically use of super keyword , for this keyword i can think of it as a pointer. One more question is that when i use this keyword inside the System.out.println(this) it print address in encrypted form but i use super keyword in System.out.println(super) it shows error why? – henrycharles Feb 01 '13 at 17:55
8

super() & this()

  • super() - to call parent class constructor.
  • this() - to call same class constructor.

NOTE:

  • We can use super() and this() only in constructor not anywhere else, any attempt to do so will lead to compile-time error.

  • We have to keep either super() or this() as the first line of the constructor but NOT both simultaneously.

super & this keyword

  • super - to call parent class members(variables and methods).
  • this - to call same class members(variables and methods).

NOTE: We can use both of them anywhere in a class except static areas(static block or method), any attempt to do so will lead to compile-time error.

Varun Vashista
  • 157
  • 1
  • 5
3

this keyword use to call constructor in the same class (other overloaded constructor)

syntax: this (args list); //compatible with args list in other constructor in the same class

super keyword use to call constructor in the super class.

syntax: super (args list); //compatible with args list in the constructor of the super class.

Ex:

public class Rect {
int x1, y1, x2, y2;

public Rect(int x1, int y1, int x2, int y2) // 1st constructor 
{ ....//code to build a rectangle }
}

public Rect () {   // 2nd constructor
this (0,0,width,height) // call 1st constructor (because it has **4 int args**), this is another way to build a rectangle 
}


public class DrawableRect extends Rect {

public DrawableRect (int a1, int b1, int a2, int b2) {
super (a1,b1,a2,b2) // call super class constructor (Rect class) 
}
}
rocketmanu
  • 137
  • 2
  • 3
  • 10
3

this is used to access the methods and fields of the current object. For this reason, it has no meaning in static methods, for example.

super allows access to non-private methods and fields in the super-class, and to access constructors from within the class' constructors only.

David Rabinowitz
  • 29,904
  • 14
  • 93
  • 125
3

When writing code you generally don't want to repeat yourself. If you have an class that can be constructed with various numbers of parameters a common solution to avoid repeating yourself is to simply call another constructor with defaults in the missing arguments. There is only one annoying restriction to this - it must be the first line of the declared constructor. Example:

MyClass()
{
   this(default1, default2);
}

MyClass(arg1, arg2)
{
   validate arguments, etc...
   note that your validation logic is only written once now
}

As for the super() constructor, again unlike super.method() access it must be the first line of your constructor. After that it is very much like the this() constructors, DRY (Don't Repeat Yourself), if the class you extend has a constructor that does some of what you want then use it and then continue with constructing your object, example:

YourClass extends MyClass
{
   YourClass(arg1, arg2, arg3)
   {
      super(arg1, arg2) // calls MyClass(arg1, arg2)
      validate and process arg3...
   }
}

Additional information:

Even though you don't see it, the default no argument constructor always calls super() first. Example:

MyClass()
{
}

is equivalent to

MyClass()
{
   super();
}

I see that many have mentioned using the this and super keywords on methods and variables - all good. Just remember that constructors have unique restrictions on their usage, most notable is that they must be the very first instruction of the declared constructor and you can only use one.

BigMac66
  • 1,528
  • 5
  • 19
  • 35