top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

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

0 votes
623 views
What is the difference between this() and super() in java?
posted Feb 29, 2016 by Naveen Kumar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

super() is used to call super class constructor, whereas this() used to call constructors in the same class, means to call parameterized constructors.
This is used to refer same (current) class elements(variables,methods,constructors), and Super is used to refer current super-class's elements(variables,methods,constructors).

Example:

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 . 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)
}
}

answer Feb 29, 2016 by Josita Sarwan
...