Java OOP: this() and super() Explained

🚀 Understanding this() and super() in Java When learning Object-Oriented Programming in Java, two important constructor calls every developer must understand are: 👉 this() 👉 super() Let’s break them down simply. 🔹 1️⃣ this() – Call Current Class Constructor this() is used to call another constructor within the same class. ✅ Why use it? Avoid code duplication Reuse constructor logic Improve readability 💻 Example: class Student { String name; int age; Student(String name) { this(name, 0); // Calling another constructor } Student(String name, int age) { this.name = name; this.age = age; } void display() { System.out.println(name + " " + age); } } 👉 Here, this(name, 0) calls the second constructor. 📌 Rule: this() must be the first statement inside the constructor. 🔹 2️⃣ super() – Call Parent Class Constructor super() is used to call the constructor of the parent class. ✅ Why use it? Initialize parent class variables Reuse parent constructor logic Required in inheritance 💻 Example: class Person { String name; Person(String name) { this.name = name; } } class Student extends Person { int age; Student(String name, int age) { super(name); // Calling parent constructor this.age = age; } void display() { System.out.println(name + " " + age); } } 👉 super(name) calls the Person constructor. 📌 Rule: super() must also be the first statement in constructor. If not written, Java automatically adds super() (default). 🔥 Key Differences this()super()Calls current class constructorCalls parent class constructorUsed for constructor chainingUsed in inheritanceRefers to current objectRefers to parent object 💡 Final Thought Understanding this() and super() makes constructor chaining and inheritance much clearer. As a Java learner, mastering these basics strengthens your OOP foundation 💪 #Java #OOP #Programming #BCAStudent #LearningJourney #BackendDevelopment

  • graphical user interface

To view or add a comment, sign in

Explore content categories