override new 多态

using System;

public class T
{
public virtual void zzz()
{
Console.WriteLine("t.zzz()");

}
}
public class A:T
{
public int book=6;
public A()
{
Console.WriteLine("A");

}
//虚方法
public virtual void fun()
{
Console.WriteLine("A.fun()");
}

public virtual void ggg()
{
Console.WriteLine("A.ggg()");
this.fun();

}

public virtual void yyy()
{
Console.WriteLine("A.yyy()");
this.xxx();
}
public virtual void xxx()
{
Console.WriteLine("A.xxx()");

}
public sealed override void zzz()
{
Console.WriteLine("A.zzz()");

}
}

public class B:A
{
//重新定义一个book覆盖父类的book属性
new public String book="方法有多态性,但属性不具有多态性";
public B()
{
Console.WriteLine("B");
}
//子类重写了父类的方法
public override void fun()
{
Console.WriteLine("b.fun()");
//用base引用父类的方法
base.fun();
}
//子类用new关键字覆盖了父类的方法
new public void ggg()
{
Console.WriteLine("b.ggg()");
//用base引用父类的方法
base.ggg();
}
//子类的普通方法
public void bfun()
{
Console.WriteLine("b.bfun()");
}
public override void xxx()
{
Console.WriteLine("b.xxx()");

}
}

public class C
{

public static void Main()
{
Console.WriteLine("====多态=====");
//多态,编译时a是A类型,运行时a是B类型
//通过引用变量a来访问其包含的实例属性时,系统总是试图访问它编译时类A所定义的属性,而不是它运行时类B所定义的属性.
//如果编译类型的方法被override,则访问运行类型的方法。
A a=new B();
//B重写了fun(),因此a.fun()运行的是b重写后的fun()方法
//输出b.fun() A.fun()
a.fun();

Console.WriteLine("===属性不具有多态性======");
//输出6,访问的是父类的属性
Console.WriteLine(a.book.ToString());

Console.WriteLine("=== new关键字======");

//运行A类的ggg(),B用new关键字只是覆盖了A的ggg(),所以a.ggg()运行的是a的编译类型A的方法。
//a.ggg()调用this.fun(),实际调用了B的fun(),因为fun()被override
//输出a.ggg() b.fun() a.fun()
a.ggg();

//编译错误!因为a编译时为A类型,而A类没有bfun()方法
//但a确实包含了bfun()方法,可通过反射来执行该方法
//a.bfun();

//非多态
Console.WriteLine("===非多态======");
A aa=new A();
B b=new B();
Console.WriteLine(b.book.ToString());
//正常运行AB中的方法()
aa.fun();//输出A.fun()

//aa调用this.fun(),this即是aa对象,
aa.ggg();//输出A.ggg() A.fun()
b.fun();//输出b.fun() A.fun()

Console.WriteLine("=========");
//注意这里this.fun()。this指的是b,因为b.ggg()里面有base.ggg(),将A。ggg()代入base.ggg()得到如下方法,很明显this代表的是b
//new public void ggg()
//{
//Console.WriteLine("b.ggg()");
//
//Console.WriteLine("A.ggg()");
//this.fun();
//}
b.ggg();// 输出b.ggg() A.ggg() b.fun() A.fun()

Console.WriteLine("=========");
//强类型转换
((A)b).ggg();//调用A类的方法
((A)b).xxx();//xxx()被override,所以调用的还是B的方法
//((A)b).bfyb();出错,提示A类没bfun()方法
((A)b).zzz();//输出zzz()

Console.WriteLine("=========");
//b.yyy()继承自A.故方法体如下,明显this代表的是b,所以this.xxx()即时b.xxx()
//public virtual void yyy()
//{
//Console.WriteLine("A.yyy()");
//this.xxx();
//}
b.yyy();


}
}

/*
结果:

====多态=====
A
B
b.fun()
A.fun()
===属性不具有多态性======
6
=== new关键字======
A.ggg()
b.fun()
A.fun()
===非多态======
A
A
B
方法有多态性,但属性不具有多态性
A.fun()
A.ggg()
A.fun()
b.fun()
A.fun()
=========
b.ggg()
A.ggg()
b.fun()
A.fun()
=========
A.ggg()
b.fun()
A.fun()
b.xxx()
A.zzz()
=========
A.yyy()
b.xxx()

*/

posted @ 2011-10-07 22:16  南山砍柴的  阅读(212)  评论(0)    收藏  举报