EducationBlog

banner image

Home - PageNavi (show/hide)

banner image

difference between super and this keyword in java.

Following are the notable differences between super() and this() methods in Java.
 super()this()
Definitionsuper() - refers immediate parent class instance.this() - refers current class instance.
InvokeCan be used to invoke immediate parent class method.Can be used to invoke current class method.
Constructorsuper() 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.
OverrideWhen 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. difference between super and this keyword in java. Reviewed by Pappy on September 03, 2019 Rating: 5

No comments:

Sports

3/Sports/small-col-right
Powered by Blogger.