首页 > 解决方案 > 通过实例引用访问的静态成员(使用 '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' 通过实例引用访问

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

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

标签: javaandroidandroid-studiostaticinstance

解决方案


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

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

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

RoundCapGraph.strokeWidth = strokeWidth;

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

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


推荐阅读