Local Variable Shadows Field

ID

java.local_shadows_field

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Java

Tags

code-style, naming

Description

Reports local variable declarations whose name matches an instance field declared in the enclosing class. This shadowing makes code confusing because within the local variable’s scope, the unqualified name refers to the local, not the field.

Rationale

When a local variable has the same name as a class field, the field is hidden within the local’s scope. This is a common source of initialization bugs where developers forget to use this.:

public class Account {
    private int balance;

    public void update() {
        int balance = computeNew();  // Shadows field
        // balance refers to the local, not this.balance
    }
}

Remediation

Use a different name for the local variable, or explicitly qualify field access with this.:

public class Account {
    private int balance;

    public void update() {
        int newBalance = computeNew();  // Distinct name
        this.balance = newBalance;
    }
}