多态和构造函数 [英] Polymorphism and Constructors
问题描述
我是AP Java学生,并且正在为考试做练习.我遇到了这个问题,但我不明白答案:
I am an AP Java Student and I am practicing for my exam. I came across this question and I don't understand the answer:
请考虑以下课程:
public class A
{
public A() { methodOne(); }
public void methodOne() { System.out.print("A"); }
}
public class B extends A
{
public B() { System.out.print("*"); }
public void methodOne() { System.out.print("B"); }
}
执行以下代码时输出是什么?
What is the output when the following code is executed:
A obj = new B();
正确答案是B *.有人可以告诉我方法调用的顺序吗?
The correct answer is B*. Can someone please explain to me the sequence of method calls?
推荐答案
调用B构造函数. B构造函数的第一条隐式指令是super()
(调用超类的默认构造函数).因此,调用了A的构造函数. A的构造函数调用super()
,后者调用java.lang.Object构造函数,该构造函数不输出任何内容.然后调用methodOne()
.由于对象的类型为B,因此将调用B的methodOne
版本,并打印B
.然后,B构造函数继续执行,并打印*
.
The B constructor is called. The first implicit instruction of the B constructor is super()
(call the default constructor of super class). So A's constructor is called. A's constructor calls super()
, which invokes the java.lang.Object constructor, which doesn't print anything. Then methodOne()
is called. Since the object is of type B, the B's version of methodOne
is called, and B
is printed. Then the B constructor continues executing, and *
is printed.
必须注意,从构造函数(如A的构造函数)中调用可重写方法是非常不好的做法:它在尚未构造的对象上调用方法.
It must be noted that calling an overridable method from a constructor (like A's constructor does) is very bad practice: it calls a method on an object which is not constructed yet.
这篇关于多态和构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!