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
In
DemoBs constructor,you call
super()which calls the constructor forDemoA. Since both constructors haveprintlnstatements, these two lines will get printed when creating aDemoBobject.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.