Java 通过实例引用访问的静态成员(使用';this';关键字)
在android studio中,我尝试使用setStrokeWidth设置strokeWidth。Java 通过实例引用访问的静态成员(使用';this';关键字),java,android,android-studio,static,instance,Java,Android,Android Studio,Static,Instance,在android studio中,我尝试使用setStrokeWidth设置strokeWidth。 但我得到了警告 通过实例引用访问的静态成员'com.example.ud.RoundCapGraph.strokeWidth' 问题:“this”关键字是否创建新实例并通过新实例访问变量 编辑:我真的不需要将strokeWidth变量设置为static,但我想了解为什么使用'this'关键字会产生特定的警告。正确,静态成员属于类而不是实例。此关键字不会创建新实例,但是这个。通常用于访问实例变量
但我得到了警告 通过实例引用访问的静态成员'com.example.ud.RoundCapGraph.strokeWidth' 问题:“this”关键字是否创建新实例并通过新实例访问变量
编辑:我真的不需要将strokeWidth变量设置为static,但我想了解为什么使用'this'关键字会产生特定的警告。正确,静态成员属于类而不是实例。
此关键字不会创建新实例,但是这个。
通常用于访问实例变量
因此,当编译器看到您试图通过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
}
}
编辑:您正在实例方法中设置静态
变量。这很好地表明编译器在警告您访问静态
变量时是正确的,就像它是一个实例变量一样
您应该通过static
方法设置static
变量,并通过实例方法设置实例变量。当您使用对象的实例访问静态成员时,实例将被类替换。i、 e此.strokeWidth
将替换为RoundCapGraph.strokeWidth
由于实例替换,将不会出现NullPointerException
我在:第15章,第11节:字段访问表达式中找到了对此的引用
示例15.11.1-2。接收器变量与静态字段访问无关
下面的程序演示了可以使用null引用访问类(静态)变量,而不会导致异常
使用new
操作符创建RoundCapGraph
的对象,然后使用它。@chiragsoni这是一个糟糕的想法:)问题是this'关键字是否创建新实例并通过新实例访问变量?
所以您可能需要重新编写答案:)换句话说,此
不会创建实例,除非您像此(/*…*/)
那样使用它(但这是另一个故事),当我们使用此
时,我们引用的实例对象将使用类创建。
RoundCapGraph.strokeWidth = strokeWidth;
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
}
}