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


基础教程推荐
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01