Bloomberg Interview Question

class A { public A() { foo(); } public void foo() { System.out.println("Class A"); } } class B extends A { public B(){} public void foo() { System.out.println("Class B"); } } class main { public static void main(String[] args) { A a = new B(); } } What does it print? Class A or Class B?

Interview Answers

Anonymous

Jan 11, 2013

it's absolutely Java code, no C++!! It will print ClassB, because default contructor of A will be automatically called from contructor of B (it isn't mandatory to call super default contructor from a derived default contructor). The method with the same signature overrides the base class method. If you "translate" the code to C++ without declaring as virtual the A's foo method, then it will print class A. Otherwise it will print Class B.

5

Anonymous

Nov 8, 2012

If this is C++, then it prints out A. But this looks like java and it printed B

5

Anonymous

Jan 3, 2013

I don't think it'll print anything. There's no super(), so A's constructor will never be called.

1

Anonymous

Dec 8, 2016

Class B is correct

1

Anonymous

Mar 7, 2017

Class B. First it's java style code. We can see it uses "System.out.println". If it's c++, it should be written as cout. Second the knowledge point it's inheritance. Variable a is actually defined as class B. That's why it will print Class B.

Anonymous

Nov 5, 2014

it will "class B" twice. its a Java code due to extends keyword & it is tested. The reason is: it will go to constructor of A, but then it will call foo() of B, then again constructor of B with foo() of B. I know its weird, but that's what I found!

Anonymous

Mar 4, 2015

This is not C++, Read item 9 Effective C++/Meyers. Never call virtual functions during construction or destruction. Moreover the syntax A a = new B(); won't work in C++. No viable conversion possible.

Anonymous

Aug 4, 2015

I have tried the problem and it prints Class B in JAVA atleast thats because before a class object calls its own constructor it makes sure to call the super's default constructor if any.

Anonymous

Dec 13, 2012

Its going to print Class B. What is going to happen that when we say new B() its going to call constructor of Class B, but since Class B inherit class A, so first constructor of Class A will be called ,hence function foo will be executed. Now function foo is overwritten in Class B ,so function foo defined in Class B will be executed. Hence it will print ClassB.

1

Anonymous

Dec 18, 2012

Guys, Guys!! Has anyone of you tested the code in VC? Come on it is absolutely Class A.

1

Anonymous

Nov 8, 2012

It prints B

1

Anonymous

Oct 25, 2012

Class B

2

Anonymous

Nov 8, 2012

thats why you are rejected... it will definitely prints out Class A, if the fun is defined as virtual, it would print out class B

3