超级论证

时间:2014-02-16 22:48:29

标签: java constructor super

请告诉我,什么不能在方法超级参数中传递?为什么这段代码不能编译?

class Base {
    static {
        System.out.println("Static");
    }
    public Base(String s) {
        System.out.println("Base " + s);
    }
}

class Sub extends Base {
    private final String Str = "Constructor";
    public Sub(Str) { // Error here
        super(Str);
        System.out.println("Sub " + Str);
    }
}


    public class Application {
    public static void main(String[] args) {
        Base B = new Sub();
    }
}

我的意思是,为什么这段代码有效:

 class Sub extends Base {
    public static String Str = "Constructor";
    public Sub() {
        super(Str);
        System.out.println("Sub " + Str);
    }
}

如果我将参数更改为静态?

3 个答案:

答案 0 :(得分:2)

您使用的语法有点不对。

public Sub(Str)

应该是

public Sub(SomeTypeHere Str)

答案 1 :(得分:0)

它应该是

private final static String Str = "Constructor";
public Sub() { // Error here
    super(Str);
    System.out.println("Sub " + Str);
}

private final String Str = "Constructor";
public Sub(String mystring) { // Error here
    super(mystring);
    System.out.println("Sub " + Str);
}

请注意:

private final String Str = "Constructor";
public Sub(String Str) { // Error here
    super(Str);
    System.out.println("Sub " + Str);
}

会隐藏您的private final String Str = "Constructor";,这可能不是您想要的。

答案 2 :(得分:0)

你想要这个

class Sub extends Base {
    private final String Str = "Constructor";
    public Sub(String Str) { // Error here
        super(Str);
        System.out.println("Sub " + Str);
    }
}
相关问题