Domanda di colloquio di 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?

Risposte di colloquio

Anonimo

11 gen 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

Anonimo

8 nov 2012

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

5

Anonimo

3 gen 2013

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

1

Anonimo

8 dic 2016

Class B is correct

1

Anonimo

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

Anonimo

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

Anonimo

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

Anonimo

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

Anonimo

13 dic 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

Anonimo

18 dic 2012

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

1

Anonimo

8 nov 2012

It prints B

1

Anonimo

25 ott 2012

Class B

2

Anonimo

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