What is the difference between the keyword “this” and “super”? Provide an example for each.

Question

What is the difference between the keyword “this” and “super“? Provide an example for each.

Give the correct answer with a detailed explanation.

 

Summary

This vs Super keyword. This keyword points to a reference of the current class, while the super keyword points to a reference of the parent class. This can be used to access variables and methods of the current class, and super can be used to access variables and methods of the parent class from the subclass. any member of the current class object from within an instance method or a constructor can be referred by using this keyword.

Explanation 

  1. Super() – refers immediate parent class instance.
  2. This() refers current class instance.
  3. Super() acts as immediate parent class constructor and should be the first line in the child class constructor.
  4. This() acts as a current class constructor and can be used in parameterized constructors.
  5. When invoking a superclass version of an overridden method the super keyword is used.
  6. When invoking a current version of an overridden method this keyword is used
  7. Can be used to invoke the immediate parent class method.
  8. Can be used to invoke the current class method

Code

class animal
{
public int c;
public int d;
public animal(int c, int d)
{
this.c=c;
this.d=d;
}
}
class base extends animal
{
public int c;
public int d;
public base(){
this (0,0); 
}
public base (int c, int d)
{
super(c+2, d+2); 
this.c=c; this.d=d;
}
public void display() {
System.out.println("Super: "+"c = "+super.c+" d= "+super.d);
System.out.println("base: "+"c= "+c+" d = "+d);
}
}
class Main
{
public static void main(String args[])
{
base a=new base();
a.display();
}
}

Output

"this" and "super"

 

 

Also, read our other blog which is to write a relational schema for the diagram.

 

Share this post

Leave a Reply

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