抽象類別不能直接執行個體化:
using System;abstract class MyClass{ }class Program{ static void Main() { /* 抽象類別不能直接執行個體化, 下面這樣會出錯 */ MyClass obj = new MyClass(); Console.ReadKey(); }}
但抽象類別可以通過子類執行個體化:
using System;abstract class Parent { }class Child : Parent { }class Program{ static void Main() { Parent obj = new Child(); Console.WriteLine(obj.ToString()); //Child Console.ReadKey(); }}
抽象方法只能包含在抽象類別中:
using System;abstract class Parent{ /* 抽象方法是隱式的虛方法, 但不能用 static 或 virtual 修飾 */ public abstract void Method1(); /* 抽象類別可以包含非抽象方法 */ public void Method2() { Console.WriteLine("Method2"); } /* 甚至可以包含靜態方法 */ public static void Method3() { Console.WriteLine("Method3"); }}class Child : Parent{ /* 實現抽象方法要使用 override */ public override void Method1() { Console.WriteLine("Method1"); }}class Program{ static void Main() { Parent.Method3(); // Method3 Child.Method3(); // Method3 Parent obj = new Child(); obj.Method1(); // Method1 obj.Method2(); // Method2 Console.ReadKey(); }}
衍生類別要實現父類的抽象方法, 除非它自己也是抽象類別:
using System;abstract class Parent{ public abstract void Method1();}abstract class Child1 : Parent{}class Child2 : Child1{ public override void Method1() { Console.WriteLine("Method1"); }}class Program{ static void Main() { Parent obj = new Child2(); obj.Method1(); //Method1 Console.ReadKey(); }}
抽象屬性:
using System;abstract class Shape{ public abstract int Area { get; }}class Rectangle : Shape{ private int FWidth, FHeight; public Rectangle(int w, int h) { FWidth = w; FHeight = h; } public override int Area { get { return FWidth * FHeight; } }}class Program{ static void Main() { Rectangle Rect = new Rectangle(20, 10); Console.WriteLine(Rect.Area); // 200 Console.ReadKey(); }}
密封類與密封成員:
using System;class Parent{ public virtual void Method1() { Console.WriteLine("Method1"); } public virtual void Method2() { Console.WriteLine("Method2"); } public virtual void Method3() { Console.WriteLine("Method3"); }}class Child1 : Parent{ /* 下面兩個方法可以繼續覆蓋 */ public override void Method1() { Console.WriteLine("New Method1"); } public override void Method2() { Console.WriteLine("New Method2"); } /* 此方法已用 sealed 禁止了繼續覆蓋, 也就是取消了虛函數的特性 */ public sealed override void Method3() { Console.WriteLine("New Method3"); }}/* 此類用 sealed 定為密封類, 不能再有衍生類別; 不管其內部的性質如何 */sealed class Child2 : Child1{ public override void Method1() { Console.WriteLine("New New Method1"); } public sealed override void Method2() { Console.WriteLine("New New Method2"); }}class Program{ static void Main() { Child2 obj = new Child2(); obj.Method1(); // New New Method1 obj.Method2(); // New New Method2 obj.Method3(); // New Method3 Console.ReadKey(); }}