你能举几个模糊的例子(代码片段)吗?
我读过JLS,但我不明白这个概念.JLS没有提供代码示例.
隐藏在Base和Derived类的字段之间.
阴影位于字段和局部变量之间.
模糊 - 在什么(?)和什么(?)之间
SIDELINE:有趣的是,JLS表示如果隐藏来自父类的相应字段,则不会继承:
阴影与隐藏不同(§8.3,§8.4.8.2,§8.5,§9.3,§9.5),它仅适用于否则将被继承但不是因为子类中的声明的成员.阴影也不同于模糊(第6.4.2节).
我也知道类名,方法名和字段名都在不同的名称空间中:
// no problem/conflict with all three x's
class x {
void x() { System.out.println("all fine"); }
int x = 7;
}
Run Code Online (Sandbox Code Playgroud)
例子:
最后找到了一个例子,有些解释什么声称是模糊(它会导致编译错误):
class C {
void m() {
String System = "";
// Line below won't compile: java.lang.System is obscured
// by the local variable String System = ""
System.out.println("Hello World"); // error: out can't be resolved
}
}
Run Code Online (Sandbox Code Playgroud)
上述情况可以通过使用完全限定名称java.lang.System或通过静态导入System.out来解决.如果我们碰巧也有变量叫做java和out,那么这些变通办法都不会起作用,也无法访问System.out.println.
鉴于 JLS 中的解释:
简单名称可能出现在可能被解释为变量、类型或包的名称的上下文中。
一个简单的例子可以是:
int String = 0;
String name = "2";
//Will print 0 as per the JLS
//Would fail without the obscured String variable
System.out.println(String);
Run Code Online (Sandbox Code Playgroud)
String其中,作为类的简单名称的标识符java.lang.String可以说在局部变量的声明中被掩盖了String。
正如 JLS 所说,模糊发生在类型和包之间,或者局部变量和类型之间。下面是第二种隐藏类型的简单示例,其中局部变量a隐藏了同名的类:
class Foo {
class a {
}
int x() {
int a = 0;
}
}
Run Code Online (Sandbox Code Playgroud)