Google Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Written Test
Well my C# code produced "A B C".
Where class C "has an instance of A as its private member" <- this line is a little a ambiguous in the problem description.
Actually, even if class B has an instance of A as its private member.. The output was still "A B C"
Well Mr. Wills product of your code was right but not the language. As far as I know Google mostly uses Java, C/C++, Python. C++ will return BAC.
ABC, when A is instantiated during declaration
BAC, when A is instantiated in C's constructor
class A
{
public A()
{
Console.Write("A");
}
}
class B
{
public B()
{
Console.Write("B");
}
}
class C : B
{
A a = new A();
// A a;
public C()
{
//a = new A();
Console.Write("C");
}
}
Since problem is clearly saying C is having the instance of A class as private, so we are not considering it should be in constructor of C class:-
Output will be:- BAC
Code:-
public class A {
public A(){
System.out.println("A");
}
}
public class B {
public B(){
System.out.println("B");
}
}
public class C extends B{
private A a=new A();
public C(){
System.out.println("C");
}
public static void main(String arr[]){
C obj=new C();
}
}
Since problem is clearly saying C is having the instance of A class as private, so we are not considering it should be in constructor of C class:-
Output will be:- BAC
Code:-
public class A {
public A(){
System.out.println("A");
}
}
public class B {
public B(){
System.out.println("B");
}
}
public class C extends B{
private A a=new A();
public C(){
System.out.println("C");
}
public static void main(String arr[]){
C obj=new C();
}
}
Just adding to the BAC consensus with my explanation.
If the interviewer asked why does it have to be this way?
My answer would be:
1) The parent class B must be constructed first to enable access to inherited elements during C's initialization => B;
2) The member variable *instance* A ("instance" means A is not an uninitialized reference*) of the class C must be called before the classes constructor or they can't be operated on in the constructer => A
3) The constructer C has the pre requisites required and can be invoked => C
* As some have pointed out *if* A was a pointer its constructer would not be called until A is explicitly created. But a pointer to A is not equivalent to an "instance of A" which the question references.
It should print B A C.
- johnny drama November 03, 2012confirmed it on an actual program!