C#語言初級入門(3)
2024-07-21 02:20:24
供稿:網友
在這最后一個例子中,我們來看看c#的抽象和多態性。首先我們來定義一下這兩個新的術語。抽象(abstract)通過從多個對象提取出公共部分并把它們并入單獨的抽象類中實現。在本例中我們將創建一個抽象類shape(形狀)。每一個形狀都擁有返回其顏色的方法,不論是正方形還是圓形、長方形,返回顏色的方法總是相同的,因此這個方法可以提取出來放入父類shape。這樣,如果我們有10個不同的形狀需要有返回顏色的方法,現在只需在父類中創建一個方法。可以看到使用抽象使得代碼更加簡短。
在面向對象編程領域中,多態性(polymorphism)是對象或者方法根據類的不同而作出不同行為的能力。在下面這個例子中,抽象類shape有一個getarea()方法,針對不同的形狀(圓形、正方形或者長方形)它具有不同的功能。
下面是代碼:
public abstract class shape {
protected string color;
public shape(string color) {
this.color = color;
}
public string getcolor() {
return color;
}
public abstract double getarea();
}
public class circle : shape {
private double radius;
public circle(string color, double radius) : base(color) {
this.radius = radius;
}
public override double getarea() {
return system.math.pi * radius * radius;
}
}
public class square : shape {
private double sidelen;
public square(string color, double sidelen) : base(color) {
this.sidelen = sidelen;
}
public override double getarea() {
return sidelen * sidelen;
}
}
/*
public class rectangle : shape
...略...
*/
public class example3
{
static void main()
{
shape mycircle = new circle("orange", 3);
shape myrectangle = new rectangle("red", 8, 4);
shape mysquare = new square("green", 4);
system.console.writeline("圓的顏色是" + mycircle.getcolor()
+ "它的面積是" + mycircle.getarea() + ".");
system.console.writeline("長方形的顏色是" + myrectangle.getcolor()
+ "它的面積是" + myrectangle.getarea() + ".");
system.console.writeline("正方形的顏色是" + mysquare.getcolor()
+ "它的面積是" + mysquare.getarea() + ".");
}
}
中國最大的web開發資源網站及技術社區,