多态性和构造函数 [英] Polymorphism and Constructors

查看:29
本文介绍了多态性和构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆