Polymorphism and Constructors

后端 未结 2 817
栀梦
栀梦 2020-12-28 07:53

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:

Consider the following classes:

<         


        
相关标签:
2条回答
  • 2020-12-28 08:42

    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.

    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.

    0 讨论(0)
  • 2020-12-28 08:49

    The base class must be constructed before the derived class.

    First A() is called which calls methodOne() which prints B.

    Next, B() is called which prints *.

    0 讨论(0)
提交回复
热议问题