Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism and Constructors

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?

like image 730
user1104775 Avatar asked May 01 '12 21:05

user1104775


People also ask

Can constructor is a polymorphism?

No, constructor overriding is not possible in Java, so whether it is runtime polymorphism or not is out of question.

Which constructor is called in polymorphism?

The B constructor is called. The first implicit instruction of the B constructor is super() (call the default constructor of super class).

What is constructor and polymorphism in Java?

before inheritance and polymorphism were introduced. A. constructor for the base class is always called in the constructor for a. derived class, chaining upward so that a constructor for every base class is. called.

What is polymorphism and example?

In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. Like a man at the same time is a father, a husband and an employee.


2 Answers

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.

like image 152
JB Nizet Avatar answered Nov 15 '22 15:11

JB Nizet


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

like image 38
Pubby Avatar answered Nov 15 '22 14:11

Pubby