【发布时间】:2012-12-20 23:34:37
【问题描述】:
我们看下面的Java代码sn-p。
package trickyjava;
class A
{
public A(String s)
{
System.out.println(s);
}
}
final class B extends A
{
public B()
{
super(method()); // Calling the following method first.
}
private static String method()
{
return "method invoked";
}
}
final public class Main
{
public static void main(String[] args)
{
B b = new B();
}
}
按照惯例,Java 中的 super() 构造函数必须是相关构造函数主体中的第一条语句。在上面的代码中,我们调用了 super() 构造函数参数列表本身 super(method()); 中的 static 方法。
表示在构造函数B()中对super的调用中,正在调用一个方法 在调用 super 之前调用!这应该被编译器禁止,但效果很好。这在某种程度上等同于以下陈述。
String s = method();
super(s);
但是,导致编译时错误表明“对 super 的调用必须是构造函数中的第一条语句”是非法的。为什么?为什么它等效的 super(method()); 是有效的并且编译器不再抱怨?
【问题讨论】:
-
super是构造函数中的第一条语句,尽管没有被首先调用。规范声明The first statement of a constructor body may be an explicit invocation of another constructor ...,而不是必须首先调用它。