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

查看:707
本文介绍了通过实例引用访问静态成员(使用'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天全站免登陆