c# 的继承和覆写与java有微妙的不同
c# 继承 覆写 父类方法
在java中,任何类,只要不是被声明为final,并且构造函数不是private,就可以被继承。继承下来的类,可以覆写父类中的非private方法。
然而,在c sharp中,你只能覆写父类中指定为virtual的方法。下面这个例子来源于java,我把它改写成为c sharp版本了。
using System;
using System.Collections.Generic;
using System.Text;
namespace poly
{
class Program
{
public static void tune(Instrument i)
{
i.play(Note.C_SHARP);
}
static void Main(string[] args)
{
Wind wind = new Wind();
Program.tune(wind);
Program.tune(new Rain());
}
}
class Note
{
private int value;
private Note(int val)
{
value = val;
}
public static Note
MIDLE_C = new Note(0),
C_SHARP = new Note(1),
B_PLAN = new Note(2);
public override string ToString()
{
return value.ToString();
}
}
class Instrument
{
public virtual void play(Note n)
{
Console.WriteLine("Instrument.play() @ " + n);
}
}
class Wind : Instrument
{
public override void play(Note n)
{
Console.WriteLine("Wind.play() @ " + n);
}
}
class Rain : Instrument
{
public override void play(Note n)
{
Console.WriteLine("Rain.play() @ " + n);
}
}
}