Difference between super() and this() in Java

Here, We are going to talk about super() and this() in Java and the basic differences between them.

super() in Java

This keyword helps a subclass refer to its immediate superclass. It has two general forms:-The first is used to call the superclass constructor. The second is used to access even the private data members of the parent class.super should be the first statement executed in the constructor of the subclass.

example:-

class parent
{
void A(){
System.out.println("Hello");
}
}
class child extends parent
{
void A()
{
super.A();// super is used to access the member A() of parent class
System.out.println("How are you");
}
}
class B
{
public static void main(String[] args)
{
child ob=new child();//creating the object of child class
ob.A();
}
}
Output:-

Hello

How are you

this() in Java

The this() keyword is used to refer to the current object in a method or a constructor. It helps to reduce the confusion regarding variable names. We can use the same name to refer to different class attributes.

example:-

class A
{
int a;
int b;
A(int a,int b)
{
this.a=a;// this here refers to the current object
this.b=b;
}// the value of a and b for both the objects will be set differently.
public static void main (String[] args)
{
A ob=new A(5,7);
A ob2=new A(8,10);
System.out.println("the value of a and b for object 1 is");
System.out.println("a="+ob.a+"\t"+"b="+ ob.b);
System.out.println("the value of a and b for object 2 is");
System.out.println("a="+ob2.a+ "\t"+"b="+ob2.b);
}
}
output:-

the value of a and b for object 1 is
a=5 b=7
the value of a and b for object 2 is
a=8 b=10

Summarize: differences between super() and this()

1.super() refers to the immediate parent class while this refers to the object of the current class.

2.super() can be used to call the methods of immediate parent class while this is used to call the methods of the current class.

3.super() refers to the constructor of the base class while this refers to the constructor of the current class.

Leave a Reply

Your email address will not be published. Required fields are marked *