What is the difference between super and this, keywords in Java?

Java 8Object Oriented ProgrammingProgramming

The this is a keyword in Java which is used as a reference to the object of the current class. Using it you can −

  • Differentiate the instance variables from local variables if they have same names, within a constructor or a method.
  • Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation.

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);
   }
}

The super is a keyword in Java which is used as a reference to the object of the super class. Like the this keyword −

  • It is used to differentiate the members of superclass from the members of subclass, if they have same names.
  • It is used to invoke the superclass constructor from subclass.

Example

Live Demo

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
raja
Published on 29-Dec-2017 04:59:07
Advertisements