字段名称与局部变量相同时如何访问字段? [英] How to access field whenever its name is same with local variable?

查看:36
本文介绍了字段名称与局部变量相同时如何访问字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字段和一个同名的局部变量.如何进入该领域?

I have a field and a local variable with same name. How to access the field?

代码:

String  s = "Global";
private void mx()
{
   String  s = "Local";
   lblB.setText(s); // i want global
}

在 C++ 中使用 :: 操作符如下:

In c++ use :: operator like following:

::s

在 Java 中是 :: 运算符吗?

Is were :: operator in Java?

推荐答案

那不是全局变量 - 它是一个实例变量.只需使用this:

That's not a global variable - it's an instance variable. Just use this:

String  s = "Local";
lblB.setText(this.s);

(参见 JLS 部分15.8.3this的含义.)

对于静态变量(这是人们在谈论全局变量时通常的意思),您可以使用类名来限定变量名:

For static variables (which are what people normally mean when they talk about global variables), you'd use the class name to qualify the variable name:

String  s = "Local";
lblB.setText(ClassDeclaringTheVariable.s);

在大多数情况下,我不喜欢使用与实例或静态变量同名的局部变量,但值得注意的例外是构造函数和设置器,这两者对于具有相同名称的参数通常是有意义的作为实例变量:

In most cases I prefer not to have a local variable with the same name as an instance or static variable, but the notable exception to this is with constructors and setters, both of which often make sense to have parameters with the same name as instance variables:

public class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

这篇关于字段名称与局部变量相同时如何访问字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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