通过实例引用访问的静态成员(使用“this”关键字)

Tik*_*imo 3 java static android instance android-studio

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
   }
}
Run Code Online (Sandbox Code Playgroud)

在 android studio 中,我尝试使用 setStrokeWidth 设置strokeWidth。
但我收到警告 静态成员 'com.example.ud.RoundCapGraph.strokeWidth' 通过实例引用访问

问题:'this' 关键字是否通过新实例创建新实例并访问变量?

编辑:我真的不需要将strokeWidth变量设置为静态,但我想了解为什么使用'this'关键字会产生特定的警告

Era*_*ran 5

this关键字不会创建新实例,但this.通常用于访问实例变量。

因此,当编译器发现您尝试通过 访问static变量时this.,它假定您可能犯了一个错误(即您的意图是访问实例变量),因此它会发出警告。

访问static变量的更好方法是:

RoundCapGraph.strokeWidth = strokeWidth;
Run Code Online (Sandbox Code Playgroud)

编辑:您正在static实例方法中设置变量。这是一个很好的迹象,表明编译器警告您访问static变量是正确的,就好像它是一个实例变量一样。

您应该static通过static方法设置变量,并通过实例方法设置实例变量。