Java this Keyword Explained with Example

📌 Understanding the this Keyword in Java (with a simple example) In Java, the this keyword is a reference to the current object of a class. It’s commonly used to differentiate instance variables from method or constructor parameters when they share the same name. Let’s look at a simple example 👇 class Employee { String name; int age; // Constructor Employee(String name, int age) { this.name = name; this.age = age; } void display() { System.out.println("Name: " + this.name); System.out.println("Age: " + this.age); } public static void main(String[] args) { Employee emp = new Employee("Vishnu", 28); emp.display(); } } 🔍 What’s happening here? this.name refers to the instance variable of the current object. name (without this) refers to the constructor parameter. Without this, Java would get confused between the two variables. Using this makes the code clear, readable, and bug-free. ✅ Why this is important? Avoids variable shadowing Improves code clarity Helps in constructor chaining and method calls Essential for writing clean object-oriented code Mastering small concepts like this builds a strong Java foundation 💪 #Java #OOP #Programming #Backend #Learning #CleanCode

To view or add a comment, sign in

Explore content categories