为了更能体现出列子的价值,我列出了3个实例类和一个接口
Door:
//我用abstract来修饰它的抽象性
public abstract class Door
{
public string Name;
public double Height;
public double Width;
public abstract string Open();//抽象方法没有方法体
public abstract string Close();
}
GlassDoor:
public class GlassDoor : Door
{
//抽象类必须由其子类实现它的抽象方法
public override string Open()
{
return "玻璃门打开";
}
public override string Close()
{
return "玻璃门关闭";
}
}
AlarmDoor:
public class AlarmDoor : Door, Ialarm
{
public override string Open()
{
return "防盗门打开";
}
public override string Close()
{
return "防盗门关闭";
}
public string Alarm()
{
return "警报器!!!";
}
}
IAlarm接口警报器:
public interface Ialarm
{
string Alarm();
}
前面工作做好了,后面是代码类;
aspx页面设计:
<body>
<form id="form1" runat="server">
<div>
AlarmDoor:<br />
<asp:Label ID="Label1" runat="server" ></asp:Label><br />
<asp:Label ID="Label2" runat="server" ></asp:Label><br />
<asp:Label ID="Label3" runat="server" ></asp:Label><br />
GlassDoor:<br />
<asp:Label ID="Label4" runat="server" ></asp:Label><br />
</div>
</form>
</body>
后台.cs代码:
protected void Page_Load(object sender, EventArgs e)
{
AlarmDoor ad = new AlarmDoor();
Label1.Text = ad.Open();
Label2.Text = ad.Close();
Label3.Text = ad.Alarm();
GlassDoor gd = new GlassDoor();
Ialarm alarmDevice = gd as Ialarm;
if (alarmDevice != null)
{
Label4.Text = alarmDevice.Alarm();
}
else
{
Label4.Text = "该设备没有报警功能!";
}
}
例子虽小,接口和抽象类,抽象方法都体现出来,希望有帮助