this | this() |
A reference variable used to invoke instance members. | It is used to invoke the constructor of same class. |
It must be used inside instance method or instance block or constructor. | It must be used inside the constructor. |
super | super() |
A reference variable used to invoke instance members of Parent class from Child class. | It is used to invoke the constructor of same class. |
It must be used inside instance method or instance block or constructor of Child class. | It must be used inside Child class constructor. |
super():
- In inheritance, we always create Object to Child class.
- In Child object creation process, we initialize instance variables of by invoking Parent constructor from Child constructor using super().
class Parent { int a, b; Parent(int a, int b) { this.a = a; this.b = b; } } class Child extends Parent { int c, d; Child(int a, int b, int c, int d) { super(a, b); this.c = c; this.d = d; } void details() { System.out.println(“a val : ” + super.a); System.out.println(“b val : ” + super.b); System.out.println(“c val : ” + this.c); System.out.println(“d val : ” + this.d); } } class Main { public static void main(String[] args) { Child obj = new Child(10, 20, 30, 40); obj.details(); } } |