virtual:使用此關鍵字,可以使其在衍生類別中被重寫.
abstract:抽象方法,由子類重寫,或繼續為抽象方法存在,並由其子子類實現.
override: 重寫父類方法,屬性,或事件的抽象實現或虛方法.
new:顯式隱藏從父類繼承的成員.
後台代碼:
public abstract class Animal{ public abstract void Eat(); public virtual void Sleep() { HttpContext.Current.Response.Write("動物正在睡覺!<hr/>"); }}public class Horse : Animal{ public override void Eat() { HttpContext.Current.Response.Write("馬在吃草!<br/>"); } public override void Sleep() { HttpContext.Current.Response.Write("馬是站著睡覺!<hr/>"); }}public class Cat : Animal{ public override void Eat() { HttpContext.Current.Response.Write("貓在吃食!<br/>"); } public new void Sleep() { HttpContext.Current.Response.Write("貓是趴著睡覺的!<hr/>"); }}
前台調用 |
效果 |
protected void Page_Load(object sender, EventArgs e) { Animal an1 = new Horse(); an1.Eat(); an1.Sleep(); Animal an2 = new Cat(); an2.Eat(); an2.Sleep(); Horse an3 = new Horse(); an3.Eat(); an3.Sleep(); Cat an4 = new Cat(); an4.Eat(); an4.Sleep(); } |
|
補充:
當sealed修飾方法時,sealed必須與override一起使用.
sealed將使您能夠允許類從您的類繼承,並防止它們重寫特定的虛方法或虛屬性
public class Cat : Animal{ public sealed override void Eat() { HttpContext.Current.Response.Write("貓在吃食!<br/>"); } public new void Sleep() { HttpContext.Current.Response.Write("貓是趴著睡覺的!<hr/>"); }}public class LitCat : Cat{ public new void Sleep() { HttpContext.Current.Response.Write("貓是趴著睡覺的!<hr/>"); }}
此時,在LitCat類中,就不會出現override Eat方法了.