A question about method overriding in c#
class xxx
{
public virtual void function1()
{
// Some code here
}
}
class yyy : xxx
{
public override void function1()
{
// some code here
}
}
class result
{
public result(){}
// In the main i write as
xxx x开发者_运维百科obj = new yyy();
xobj.function1(); // by calling this function1 in yyy will invoked
yyy yobj = new xxx();
yobj.function1() // which function will be called here
}
ple
Well, first of all:
yyy yobj = new xxx();
yobj.function1();
will cause a compile error. yyy
is a xxx
, but xxx
is not a yyy
.
Secondly:
xxx xobj = new yyy();
xobj.function1();
will cause function1()
of class xxx
to be executed because the variable is of type xxx
. to call the method on class yyy
you will need to cast the variable to type yyy
xxx xobj = new yyy();
((yyy)xobj).function1();
This is a classic common misconception about inheritance. Inheritance is not bidirectional. By this I mean that a sub class is a type of a super class .. but it is not true the other way around.
public class Base
{
}
public class Sub : Base
{
}
Base baseObj = new Base(); //this is just fine
Base subAsBase = new Sub(); //this is just fine, a Sub is a type of Base
Sub subAsBase = new Base(); //this will spit a compile error. A Base is NOT a type of Sub, it is the other way around.
Likewise, I could perform the following casting:
Base baseObj = null;
Sub subObj = new Sub();
baseObj = subObj; //now I am storing a sub instance object in a variable declared as Base
Sub castedSubObj = baseObj as Sub; //simply casted it back to it's concrete type
You cannot cast xxx to yyy, so yyy yobj = new xxx();
won't compile
精彩评论