this() and super() call in java


this( ) call :

In java ‘this()’ is used to call a constructor from another overloaded constructor in the same class. It should be the first statement within the constructor.

public class Car {
public static void main(String[] args) {
Toyota obj1=new Toyota(6,16);
Toyota obj2=new Toyota();
System.out.println(obj1.getvalues()); // output 6
System.out.println(obj2.getvalues()); //output 0
}
}

class Toyota{
private int height;
private int width;
private int no_of_seats;
private int no_of_doors;

//first constructor calls the second constructor.
public Toyota(){
this(0,0);
}

//second constructor; calls the third constructor.
public Toyota(int no_of_seats,int no_of_doors){
this(0,0,no_of_seats,no_of_doors);
}
//third constructor; within this constructor the variables are initialized.
public Toyota(int height,int width,int no_of_seats,int no_of_doors){
this.height=height;
this.width=width;
this.no_of_seats=no_of_seats;
this.no_of_doors=no_of_doors;
}
public int getvalues() {
return no_of_seats ;
}
}

super( ) call:

It is used to call the constructor of the parent class. from the subclass.

public class Bus {
public static void main(String[] args) {
Minibus m=new Minibus(3,5);
m.getvalues();
}
}
class Vehicle{
private int no_of_seats;
private int no_of_windows;

public Vehicle(int no_of_seats,int no_of_windows) {
this.no_of_seats=no_of_seats;
this.no_of_windows=no_of_windows;
}
}

class Minibus extends Vehicle{
private int length;
private int width;

public Minibus(int length,int width) {
this(length,width,0,0);
}

public Minibus(int length,int width,int no_of_seats,int no_of_windows) {
super(no_of_seats, no_of_windows); // Calls the constructor from the parent class.
this.length=length;
this.width=width;
}

public int getvalues() {
return width;
}
}