通过实例引用访问的静态成员(使用“this"关键字) [英] Static member accessed via instance reference (using 'this' keyword)

查看:29
本文介绍了通过实例引用访问的静态成员(使用“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.

这篇关于通过实例引用访问的静态成员(使用“this"关键字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆