java - 通过实例引用访问的静态成员(使用 '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' 关键字会产生特定警告
解决方案
this
关键字不会创建新实例,但this.
通常用于访问实例变量。
因此,当编译器看到您尝试通过 访问static
变量时this.
,它会假定您可能犯了错误(即您的意图是访问实例变量),因此会发出警告。
访问static
变量的更好方法是:
RoundCapGraph.strokeWidth = strokeWidth;
编辑:您正在static
实例方法中设置变量。这很好地表明编译器警告您访问该static
变量是正确的,就好像它是一个实例变量一样。
您应该static
通过static
方法设置变量,并通过实例方法设置实例变量。
推荐阅读
- python - Python:比较并插入一个向量与一个有序的numpy数组
- python - python pandas dataframe 制作 r(t-1).iloc[1:] = r(t).iloc[0:-1]
- python - 运行总计 Python:“TabError:缩进中制表符和空格的不一致使用”
- c++ - 函数或代码中间的代码块
- python - 如何使用 BeautifulSoup 从一段 html 代码中获取价值?
- twitter - Twitter使用Auth0获取token和secret token
- angular - 我想设置最大数量并限制在我的离子输入中使用负数
- python - 如何使用 Python 通过 Cloud Dataflow 将 CSV 文件导入 Cloud Bigtable?
- c++ - 将 10 个整数存储到数组 C++ 中的问题
- c - 使用头文件的共享内存数据