DEV Community

Arun Kumar
Arun Kumar

Posted on • Edited on

This and super uses in java

The "this" Keyword

The this keyword in Java is a reference variable that refers to the current object of a class.

Why is this keyword used?
This keyword in Java refers to the 'current object' in a method or constructor. It is used to reduce the confusion between class attributes and parameters with the same name

It has several important uses:

Main Uses of this:
1). To refer to current class instance variables (to resolve ambiguity between instance variables and parameters)

public class Student {
    String name;

    public Student(String name) {
        this.name = name; // 'this.name' refers to instance variable
    }
}
Enter fullscreen mode Exit fullscreen mode

Important Notes

a). this cannot be used in a static context (static methods or static blocks)

b). this is automatically added by the compiler in many cases (like when calling instance methods)

c). It helps make code more readable and resolves naming conflicts

d). In event handling or anonymous classes, this can refer to different objects.

The "super" Keyword

The .super keyword in Java is a reference variable that refers to the immediate parent class object. It's used to access parent class members (fields, methods, and constructors) from a subclass.

Main Uses of super
1). Accessing Parent Class Variables
Used when child and parent classes have fields with the same name:

class Parent {
    String color = "white";
}

class Child extends Parent {
    String color = "black";

    void printColor() {
        System.out.println(super.color); // prints "white" (parent)
        System.out.println(color);       // prints "black" (child)
    }
}
Enter fullscreen mode Exit fullscreen mode

2). Calling Parent Class Methods

Used to call overridden methods from the parent class:

class Parent {
    void display() {
        System.out.println("Parent method");
    }
}

class Child extends Parent {
    void display() {
        super.display(); // calls parent's display()
        System.out.println("Child method");
    }
}
Enter fullscreen mode Exit fullscreen mode

super vs this

  • Feature super this
  • Reference Immediate parent class Current class instance
  • Constructor Calls parent constructor Calls current class constructor
  • Variables Accesses parent class variables Accesses current class variables
  • Methods Calls overridden parent methods Calls current class methods

Understanding super is essential for proper inheritance and method overriding in Java.

Top comments (1)

Collapse
 
manikandan_a8f99e0153ef77 profile image
MANIKANDAN

🎉