我写了一小段代码:
System out = null;
out.out.println("Hello");
这工作正常,正在控制台上打印“Hello”。
现在在我的程序或我的范围内,有两个名为out. 一个是对象,System另一个是对象PrintStream。
为什么我没有收到编译器错误/运行时错误Duplicate local variable out.?
我在这里想念什么?
我写了一小段代码:
System out = null;
out.out.println("Hello");
这工作正常,正在控制台上打印“Hello”。
现在在我的程序或我的范围内,有两个名为out. 一个是对象,System另一个是对象PrintStream。
为什么我没有收到编译器错误/运行时错误Duplicate local variable out.?
我在这里想念什么?
不,只有一个名为 的对象out,即System-type 局部变量。另一个是 named out.out,它不直接“在您的范围内”。
这没有理由导致编译时错误。
(顺便说一句,通过引用调用静态方法/引用静态字段null并不是很好的做法,这很令人困惑。)
您没有在同一范围内声明两个具有相同名称的变量。out您声明的在程序的范围内,而 PrintWriterout在 System 类中声明为静态变量。
例如..
class System {
....
PrintWriter out ;
....
}
class YourClass{
public void yourMethod()
{
System out = null;
// as PrintWriter's out is declared as static, so you can call like this
// without any run-time exception such as NullPointerException
out.out.println("Hello");
}
}
为了简单起见:您正在System以合法但不受欢迎的方式访问类的静态字段:通过System使用类型变量而不是字面意义上的类名来限定它System。这两个表达式的含义完全相同:
((System)null).out.println("a");
System.out.println("a");