Following are the notable differences between super() and this() methods in Java.
super() | this() | |
---|---|---|
Definition | super() - refers immediate parent class instance. | this() - refers current class instance. |
Invoke | Can be used to invoke immediate parent class method. | Can be used to invoke current class method. |
Constructor | super() acts as immediate parent class constructor and should be first line in child class constructor. | this() acts as current class constructor and can be used in parametrized constructors. |
Override | When invoking a superclass version of an overridden method the super keyword is used. | When invoking a current version of an overridden method the this keyword is used. |
Example
class Superclass { int age; Superclass(int age) { this.age = age; } public void getAge() { System.out.println("The value of the variable named age in super class is: " +age); }
Example
class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
public void getAge() {
System.out.println("The value of the variable named age in super class is: " +age);
}
}
public class Subclass extends Superclass {
Subclass(int age) {
super(age);
}
public static void main(String argd[]) {
Subclass s = new Subclass(24);
s.getAge();
}
}
Output
The value of the variable named age in super class is: 24
difference between super and this keyword in java.
Reviewed by Pappy
on
September 03, 2019
Rating:
No comments: