通过实例引用访问静态成员(使用'this'关键字)
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
}
}
在android studio中,我尝试使用setStrokeWidth设置strokeWidth.
但是我得到警告
通过实例引用访问静态成员'com.example.ud.RoundCapGraph.strokeWidth'
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
问题:'this'关键字是否创建新实例并通过新实例访问变量?
Question : Does 'this' keyword make new instance and access variable via new instance?
已我确实不需要将strokeWidth变量设置为静态,但是我想了解为什么使用'this'关键字会产生特定的警告
EDITED : I don't really need to set strokeWidth variable static, but I want to understand why using 'this' keyword produce particular warning
this
关键字不会创建新实例,但是this.
通常用于访问实例变量.
this
keyword doesn't create a new instance, but this.
is usually used to access instance variables.
因此,当编译器看到您尝试通过this.
访问static
变量时,它假定您可能犯了一个错误(即,您打算访问实例变量),因此它发出警告它.
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.
访问static
变量的更好方法是:
A better way to access the static
variable is:
RoundCapGraph.strokeWidth = strokeWidth;
您正在实例方法中设置static
变量.这很好地表明编译器正确警告您访问static
变量,就像它是实例变量一样.
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.
您应该通过static
方法设置static
变量,并通过实例方法设置实例变量.
You should set static
variables via static
methods, and set instance variables via instance methods.