gpt4 book ai didi

java - 方法局部内部类隐藏方法字段

转载 作者:行者123 更新时间:2023-11-30 07:53:16 26 4
gpt4 key购买 nike

给定以下类定义

public class MethodLocalAccess {

int m = 10;

String show(){
final int m = 20;
final int n = 30;
class MyClass{
int m = 40;
String someOtherMethod(){
return "" + m + n + this.m + MyClass.this.m + MethodLocalAccess.this.m;
}
}

MyClass object = new MyClass();
return object.someOtherMethod();
}

public static void main(String[] args) {
System.out.println(new MethodLocalAccess().show());
}

}

产生输出 4030404010,这是相当确定的原因。我想知道局部变量 final int m = 20; 是否可以在内部类中访问。

换句话说,在局部方法内部类中声明的字段与局部方法变量的名称相同,将永久隐藏后者。

最佳答案

您指的是变量阴影 ( link )。

If a declaration of a type (such as a member variable or a parameter name) in a particular scope (such as an inner class or a method definition) has the same name as another declaration in the enclosing scope, then the declaration shadows the declaration of the enclosing scope. You cannot refer to a shadowed declaration by its name alone.

一旦你隐藏了一个变量,如果可能的话,如果不显式指定它的范围就不能再访问它。在这种情况下,唯一的解决方案是重命名外部或内部变量。

关于java - 方法局部内部类隐藏方法字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44942441/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com