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.
这篇关于多态性和构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:多态性和构造函数


- 如何指定 CORS 的响应标头? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 转换 ldap 日期 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 获取数字的最后一位 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01