“this” and “super”- keyword

“this” keyword:

It is to distinguish difference between local and instance data variable when their names are alike/same.

“this” is an object of that class.

It can also call methods.

“this” keyword is optional for a method call within a class.

It can refer properties of its own class.

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

EXAMPLE OF “this” KEYWORD:

public class A
{
int a=1; // instance variable
int b=2; // instance variable
int add()
{
int a=3; // local variable
int b=2; // local variable
int c= a+ this.a +b + this.b;
return c;
}
int sub()
{
int c= a+b;
return c;
}
}

Why we need “this” keyword?

  • Invoke current class constructor
  • Invoke current class method
  • Return the current class object
  • Pass an argument in the method call
  • Pass an argument in the constructor call

“super” keyword:

To call the instance variables and methods of parent class from child class.

If your method overrides one of its superclass’s methods, you can invoke the overridden method through the use of the keyword super.

“super” keyword always refers the properties of parent class only.

EXAMPLE OF “super” KEYWORD:

public class A //parent class
{
int a=1; // instance variable
}
class B extends A
{
int a=2; // instance variable
int m()
{
int a= 3;
println(a + this.a + super.a); // local + own class instance var + parent class instance var
}
}

Quick learn about “super” keyword:

  • In java super keyword refers immediate parent class objects
  • In java super keyword is only used in case of Inheritance
  • Super keyword in java accesses parent class variables, methods or constructor
  • Super call for the parent class constructor should be the first line in the child class constructor
  • If you don’t specify super() in child class, JVM will provide it implicitly

Difference between “this and “super”:

Leave a comment

Design a site like this with WordPress.com
Get started