noobprogrammer
noobprogrammer

Reputation: 523

Arraylist output is not as expected

The output produced from this code is not making sense, perhaps due to my lack of understanding. Correct me if I am wrong

import java.util.*;
class DemoA
{
  public DemoA(){
    System.out.println("DemoA object created");
  }
  public String methodA() {
    return "methodA in DemoA";
  }
}
class DemoB extends DemoA
{
  public DemoB(){
    super();
    System.out.println("DemoB object created");
  }
  public String methodA() {
   return "methodA in subclass (DemoB)";
  }
}
public class ExamQ1b
{
  public static void main(String[] args) {
    ArrayList<DemoA> aList = new ArrayList<DemoA>();
    aList.add(new DemoA());
    aList.add(new DemoB());
    for (DemoA obj: aList)
      System.out.println(obj.methodA());
  }
}

The output is

DemoA object created
DemoA object created
DemoB object created
methodA in DemoA
methodA in subclass (DemoB)

At first I didn't understand how the output came about, but then i used the debugging feature and found why it is behaving such a way and discovered something rather confusing (not amazing).

Why is that these lines of code are producing the output?

aList.add(new DemoA());
    aList.add(new DemoB());

the output from the above lines are these, but in my thinking these should just add to the list not produce any output, what am I missing here?

DemoA object created
DemoA object created
DemoB object created

Upvotes: 0

Views: 86

Answers (4)

The Cat
The Cat

Reputation: 2475

In DemoBs constructor,

  public DemoB(){
    super();
    System.out.println("DemoB object created");
  }

you call super() which calls the constructor for DemoA. Since both constructors have println statements, these two lines will get printed when creating a DemoB object.

DemoA object created

DemoB object created

These lines are printed when you create the object because System.out.println("DemoB object created"); is inside the constructor method that is called when you create the object.

Upvotes: 2

dlopezgonzalez
dlopezgonzalez

Reputation: 4297

aList.add(new DemoA());

=> DemoA object created (Constructor A)

aList.add(new DemoB());

=> DemoA object created (Contructor A called by super() because DemoA is a parent class of DemoB) => DemoB object created (Contructor B)

First System.out.println(obj.methodA());

=> methodA in DemoA (methodA in DemoA)

Second System.out.println(obj.methodA());

=> methodA in DemoA (methodA in DemoB)

Upvotes: 0

JTMon
JTMon

Reputation: 3199

When you call new DemoA() you call the constructor which is outputting DemoA Created and when you instantiate a new DemoB, the super constructor is called (explicitly) in this case which outputs DemoA Created and then the DemoB constructor is called and outputs demoB created, so all is as expected

Upvotes: 0

mattg
mattg

Reputation: 1855

You have print statements in your constructors. Those get called when you write "new DemoA()"

Upvotes: 1

Related Questions