20

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:

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();

The correct answer is B*. Can someone please explain to me the sequence of method calls?

1
  • Add a print statement to the constructor of A, and it may become clearer. Commented May 1, 2012 at 21:52

2 Answers 2

40

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.

Sign up to request clarification or add additional context in comments.

1 Comment

And, the overidden method may not work the way Class A expects it to.
2

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 *.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.