Mostly used inside the constructors or methods to eliminate the confusion between instance variables and parameters with the same name. Please note that a instance variable is shadowed by a method or constructor parameter inside that particular method or constructor.
public class Example{
private String name;
public Example(String name) {
this.name = name;
}
}
Used for invoking another constructor inside a constructor.
Please note that this(params) or this() should be the first line in the constructor.
You cannot use this() / this(params) and super()/super(params) both in the same constructor.
Access the data members of parent class when both parent and child class have member with same name
Explicitly invoke constructors of parent class. super() or super(parameters) should be the first line in the constructor.
Access the method of parent class which is overridden in the child class.
Limitations of this and super
this and super cannot be used inside static methods and static blocks.
Java Code - Full Example
packagecom.java.core;publicclassExampleextendsSuperClass{privateint id =1;privateString name ="Gyan";publicExample(String name){// Compiler will add no-arg super() hereSystem.out.println("Invoking Parameterized Constructor for name:"+ name);this.name = name;}// Overridden methodpublicvoidmethod(String name){// Using this to avoid confusion with method parameter having same nameSystem.out.println("Method Parameter name:"+ name +", current Object name:"+this.name);System.out.println("Method Invoked");super.method(name);// Invoking Super Class method using super}publicExample(int id){super(id *2);// Explicitly Calling Super Class parameterized Constructor// Using this to avoid confusion with constructor parameter having same namethis.id = id;System.out.println("Invoking Parameterized Constructor for id:"+ id);}publicExample(){this(5);// Calling parameterized ConstructorSystem.out.println("Invoking No args Constructor");}publicvoidprintIds(){System.out.println("Current instance id:"+this.id +", name:"+ name);System.out.println("Super instance id:"+super.id);}publicstaticvoidmain(String[] args){System.out.println("-------------------------------------------------------");Example example1 =newExample();
example1.printIds();
example1.method("Rochit");System.out.println("-------------------------------------------------------");Example example2 =newExample(10);
example2.printIds();System.out.println("-------------------------------------------------------");Example example3 =newExample("Ram");
example3.printIds();System.out.println("-------------------------------------------------------");}}classSuperClass{int id;publicSuperClass(){System.out.println("Invoking No args SuperClass Constructor");this.id =10;}publicSuperClass(int id){System.out.println("Invoking Parameterized SuperClass Constructor");this.id = id;}publicvoidmethod(String name){System.out.println("Super Class Method Invoked");}}