DEV Community

KIRAN RAJ
KIRAN RAJ

Posted on

this and super

this:

  • this refers to current object

  • this is used to differentiating instance variables and local variable/parameters with the same name.

  • this is refers to the instance variable.

    • The this keyword can be used to call other method within the same class.

-You can refer to any member of the current object from within an
instance method or a constructor by using this.

public class Point {
    public int x = 0;
    public int y = 0;

    //constructor
    public Point(int a, int b) {
        x = a;
        y = b;
    }
}
Enter fullscreen mode Exit fullscreen mode

super:

  • To call the superclass constructor.

  • To access a method from the superclass that has been overridden in the subclass.

  • To access a field from the superclass when it is hidden by a field of the same name in the subclass.

  • If your method overrides one of its superclass methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged).
    public class Superclass {

    public void printMethod() {
        System.out.println("Printed in Superclass.");
    }
}

Here is a subclass, called Subclass, that overrides printMethod():

public class Subclass extends Superclass {

    // overrides printMethod in Superclass
    public void printMethod() {
        super.printMethod();
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {
        Subclass s = new Subclass();
        s.printMethod();    
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)