Java Variable Shadowing Explained with Example

🚀 Core Java Learning Journey Explored Variable Shadowing in Java ☕ 🔹 What is Variable Shadowing? Variable shadowing occurs when a local variable or parameter has the same name as an instance variable, hiding (shadowing) the instance variable within its scope. 📌 Why does it happen? - When method parameters or local variables use the same name as class-level variables - The local variable gets higher priority inside the method 📌 Example: class Student { int id; Student(int id) { id = id; // Shadowing happens here } } 👉 In this case, the parameter "id" shadows the instance variable "id", so the instance variable is not initialized correctly. 🔹 How to Resolve Shadowing? ✅ Use "this" keyword to refer to the current object’s instance variable class Student { int id; Student(int id) { this.id = id; // Correct way } } 🎯 Key Takeaway: Variable shadowing can lead to logical errors, and using "this" keyword helps in clearly distinguishing instance variables from local variables. Learning and growing at Dhee Coding Lab 💻 #Java #CoreJava #OOP #VariableShadowing #Programming #LearningJourney #FullStackDevelopment

To view or add a comment, sign in

Explore content categories