Pergunta de entrevista da empresa Bloomberg

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?

Respostas da entrevista

Sigiloso

11 de jan. de 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

Sigiloso

8 de nov. de 2012

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

5

Sigiloso

3 de jan. de 2013

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

1

Sigiloso

8 de dez. de 2016

Class B is correct

1

Sigiloso

7 de mar. de 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.

Sigiloso

5 de nov. de 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!

Sigiloso

4 de mar. de 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.

Sigiloso

4 de ago. de 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.

Sigiloso

13 de dez. de 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

Sigiloso

18 de dez. de 2012

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

1

Sigiloso

8 de nov. de 2012

It prints B

1

Sigiloso

25 de out. de 2012

Class B

2

Sigiloso

8 de nov. de 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