this vs super in Java: Accessing Class and Parent Class

this vs super in Java – Simple Explanation 🎯 🔹 this keyword: ▸ Refers to the current class object ▸ this.variable → access current class variable ▸ this() → call current class constructor ▸ Used to resolve naming conflicts class Student { String name; Student(String name) { this.name = name; // refers to current object } } 🔹 super keyword: ▸ Refers to the parent class object ▸ super.variable → access parent class variable ▸ super() → call parent class constructor ▸ Used to access overridden methods class Dog extends Animal { void sound() { super.sound(); // calls Animal's sound() System.out.println("Bark"); } } 🔑 Key Difference: → this = current class → super = parent class 💡 Both can access constructors, variables, and methods — but direction matters: this → inward | super → upward 🔥 Pro Tip: Use this() and super() carefully they must be the first statement in constructor. #Java #CoreJava #OOP #JavaDeveloper #BackendDeveloper #Programming

  • graphical user interface, application

You CANNOT use both this() and super() in the same constructor only one is allowed. 👉 Reason: A constructor call must be the first statement. this() calls another constructor of the same class, while super() calls the parent class constructor. If both were allowed, it would create ambiguity in constructor chaining so Java restricts it.

If a child class doesn’t define a constructor → super() is called automatically 🤯 👉 Reason: Java ensures the parent class is initialized first before creating the child object. That’s why the compiler inserts a default super() call as the first line (behind the scenes).

Nice post 🔥Using this for current class reference and super for parent class access is fundamental, especially in constructor chaining and method overriding.

See more comments

To view or add a comment, sign in

Explore content categories