tags:

views:

86

answers:

2

I was faced this question while one of recent interview :

class1
{ 
  virtual getname();
  {//code here..}
}

class2:class1
{
  overrides getname();
  {//code here..}

}
class3:class2
{
  public new getname();
  {//code here..}

}

class4
{
  class1 obj=new class3();
  obj.getname();
}

now in class4 which class's method will call ? why ? and what is call this concept in oops ?

+4  A: 

The getname in class3 will be the only one that's invoked.

It's called Method Hiding

Excerpt from link

Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword.

David Hedlund
your link suggests that because obj is of type `class1` and it's not a virtual dispatch, `class3::getname` will *not* get called. I'd guess `class2::getname`, but I'm not a C# guy.
Philip Potter
Strange that so much people approved. It would be correct if obj was declared as class3 but its declared as class1 so class2::getname is called. I finally doubt it and tested in c# 4.0 which works as expected...
VdesmedT
+2  A: 

The call is performed against the interface which, in this case, is Class1.

The object obj has two method getname : one in the Class1 interface and one in the Class3 interface. In this case, the one in the Class1 interface is called but the implementation of this method from the class1 interface has been overidden in Class2 and since the reel object is of Class3, it return the implementation made in class2.

The final answer is then Class2

In OOP, this is called "polymorphisme".

VdesmedT