class AA{
int x;
protected AA(){init (1008);}
protected void init(int x)
{
this.x = x;
}
}
class BB extends AA{
public BB() {
init(super.x * 2);
}
public void init(int x)
{
super.x = x+1;
}
}
public class Main {
public static void main(String[] args) {
BB tst = new BB();
System.out.println(tst.x);
}
}
我知道这段代码将在2019年打印。但是我不明白为什么超类构造函数在被调用时会使用de子类中的init方法而不是超类中的init方法。
但是我不明白为什么超类构造函数在被调用时会使用de子类中的init方法而不是超类中的init方法。
因为那是与正在构造的对象相关联的对象。this
在超类构造函数中,是对正在构造的子类对象的引用,因此,就像init
使用该引用的任何其他调用一样,它使用子类的init
。
请注意最后带有注释的行,这可能会有所帮助-注释说明这些行的输出:
class AA{
int x;
protected AA() {
System.out.println(this.getClass().getName()); // "BB"
System.out.println(this instanceof BB); // true
init(1008);
}
protected void init(int x)
{
this.x = x;
}
}
class BB extends AA{
public BB() {
init(super.x * 2);
}
public void init(int x)
{
super.x = x+1;
}
}
public class Main {
public static void main(String[] args) {
BB tst = new BB();
System.out.println(tst.x);
}
}
这是因为子类可以覆盖方法,通常最好避免从构造函数中调用final
非private
方法或非方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句