getting null because of this
public void setIsActive(Boolean isActive) {
isActive = isActive;
}
explain to me what is happening vs this corrected code
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
ChatGPT zei:
Great question — and a classic Java pitfall.
Here’s exactly what's going wrong and how the fix solves it.
❌ Broken Code
java
public void setIsActive(Boolean isActive) {
isActive = isActive;
}
✅ What you intended:
You meant to assign the value of the method parameter (isActive) to the instance variable isActive.
❌ What actually happens:
The code isActive = isActive; assigns the parameter to itself.
You're setting the method's local variable (isActive) equal to itself — not touching the field at all.
This means the instance field remains null, and that's why you're seeing null when you try to use or serialize the object.
✅ Correct Code
java
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
✔️ What this does:
this.isActive refers to the field of the object.
isActive refers to the parameter.
You're now assigning the value from the parameter to the object's field — which is exactly what you want in a setter.
🧠 Rule of Thumb
- Always use this.fieldName when:
The method parameter has the same name as the field.
You want to disambiguate between them.
Top comments (0)