Morgan Stanley Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Phone Interview
here the statement :
ParentTest s = new ChildTest();
is evaluated as
ParentTest s ;
s= new ChildTest();
even though the variable s refers an instance of class ChildTest, the s.x still evaluates to "0". Because variables names in Java are resolved by the reference type (it is ParentTest in this code), not the object they are referencing.this is known as Shadowing in Java
ChildTest extends ParentTest and overrides its print() method and when we call print() method from a reference variable of type ParentTest, it doesn't call print() method from ParentTest class instead it calls print() method from ChildTest subclass because object referenced by ParentTest type is a ChildTest object. This resolution happens only at runtime because object only created during runtime and called dynamic binding in Java AKA Dynamic Method Dispatch.
I know little about java, but in c++ in this case, there is no virtual function. So the result should be "0 and In Parent".
And I verfy it on my ubuntu. here is my code in c++:
class A
{
public:
int x;
void print()
{
printf("In parent, x= %d\n", x);
}
A(): x(0){}
};
class B: public A
{
public:
int x;
void print()
{
printf("In child, x= %d\n", x);
}
B():x(1){}
};
int main()
{
A* p = new B;
p->print();
delete p;
return 0;
}
Dynamic polymorphism is applicable to methods but not to variables. So the output will be "0 and In Child"
- Naresh Parimi May 15, 2014