Guilherme
Guilherme

Reputation: 7949

Java - static variable and parameter with same name

Suppose I have a Helper class as below:

public class Helper {
    private Context context;
    private static HelperListener listener;


    public Helper(Context context, HelperListener listener) {
        this.context = context;
        listener = listener; // Can't tell which one
    }
}

context and listener are variables that will be set only once, in the constructor.

context is not static, hence I can differentiate the variable from the parameter using this.context.

listener, on the other hand, is static. Is there any way to differentiate it from the parameter when it comes to static variables?

Upvotes: 14

Views: 5747

Answers (2)

anirudh
anirudh

Reputation: 4176

You could use Helper.listener = listener; although setting the value of a static variable from a constructor is not recommended.

Upvotes: 14

arshajii
arshajii

Reputation: 129507

You can qualify the static variable with the class name to differentiate it:

Helper.listener = listener;

Upvotes: 17

Related Questions