我如何隐式和显式地调用构造函数?

时间:2015-02-11 03:05:34

标签: java oop constructor

我有A类并且写了一个子类B,C.A只有一个参数化的构造函数。 C必须调用这个B的超级构造函数,B必须调用这个A的超级构造函数。现在我想用object作为参数。因此参数对象必须保存C的引用。

  

语言:java

Calss A:

public class A {

private C c;


protected A(C c) {
    this.c = c;
}
}

B类:

public class B extends A {

protected B(C c) {
    super(c);
}
}

C类:

enter image description here

现在,当我想调用构造函数时,Eclipse说:

Cannot refer to 'this' nor 'super' while explicitly invoking a constructor

如何用“this”实例调用超类构造函数。 请解释这个错误并给出解决方案。

1 个答案:

答案 0 :(得分:0)

  

如何用“this”实例调用超类构造函数。

你做不到。

  

给出解决方案。

super(this)更改为super(null)

  

我如何隐式调用构造函数

通过使用反射,就像在类对象上调用newInstance一样。或者使用工厂方法。或使用new关键字。

相关问题