C# 语法练习(12): 类[四] - 抽象类与抽象成员、密封类与密封成员
2009-02-23 08:16:48 来源:WEB开发网派生类要实现父类的抽象方法, 除非它自己也是抽象类:
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();
}
}
更多精彩
赞助商链接