Tiktrimo
Tiktrimo

Reputation: 43

Static member accessed via instance reference (using 'this' keyword)

public class RoundCapGraph extends View {
   static private int strokeWidth = 20;

   public void setStrokeWidth(int strokeWidth){
       this.strokeWidth = strokeWidth;
       //warning : static member 'com.example.ud.RoundCapGraph.strokeWidth' accessed via instance reference
   }
}

In android studio I'm trying to set strokeWidth using setStrokeWidth.
But I get warning static member 'com.example.ud.RoundCapGraph.strokeWidth' accessed via instance reference

Question : Does 'this' keyword make new instance and access variable via new instance?

EDITED : I don't really need to set strokeWidth variable static, but I want to understand why using 'this' keyword produce particular warning

Upvotes: 4

Views: 7675

Answers (3)

Eran
Eran

Reputation: 393846

this keyword doesn't create a new instance, but this. is usually used to access instance variables.

Therefore, when the compiler sees that you try to access a static variable via this., it assumes that you might have made a mistake (i.e. that your intention was to access an instance variable), so it warns about it.

A better way to access the static variable is:

RoundCapGraph.strokeWidth = strokeWidth;

EDIT: you are setting your static variable within an instance method. This is a good indication that the compiler was right in warning you about accessing the static variable as if it was an instance variable.

You should set static variables via static methods, and set instance variables via instance methods.

Upvotes: 5

Govinda Sakhare
Govinda Sakhare

Reputation: 5749

When you access static member using object's instance, the instance gets replace by Class. i.e this.strokeWidth would be replace with RoundCapGraph.strokeWidth

There will be no NullPointerException due to the instance replacement.

I found a reference to this in the Java Specification: Chapter 15, Section 11: Field Access Expressions.

Example 15.11.1-2. Receiver Variable Is Irrelevant For static Field Access

The following program demonstrates that a null reference may be used to access a class (static) variable without causing an exception

public class RoundCapGraph extends View {
   static private int strokeWidth = 20;

   public void setStrokeWidth(int strokeWidth){
       RoundCapGraph roundCapGraph = null;
       roundCapGraph.strokeWidth = strokeWidth; // NullPointerException?
       //warning : static member 'com.example.ud.RoundCapGraph.strokeWidth' accessed via instance reference
   }
}

Upvotes: 1

JakeB
JakeB

Reputation: 2113

Correct, Static members belong to the class not to an instance.

Upvotes: 0

Related Questions