close
範例一:矩形、圓形繼承形狀 (Shape)
using System;
class Shape
{
public virtual double area() { return 0.0; }
}
class Rectangle : Shape
{
double width, height;
public Rectangle(double w, double h)
{
width = w;
height = h;
}
public override double area()
{
return width * height;
}
}
class Circle : Shape
{
double r;
public Circle(double r)
{
this.r = r;
}
public override double area()
{
return 3.1416 * r * r;
}
}
class Test
{
public static void Main(string[] args)
{
Shape s = new Shape();
Console.WriteLine("s.area() = " + s.area());
Rectangle r = new Rectangle(5.0, 8.0);
Console.WriteLine("r.area() = " + r.area());
Circle c = new Circle(2);
Console.WriteLine("c.area() = " + c.area());
}
}
執行結果:
s.area() = 0
r.area() = 40
c.area() = 12.5664
範例二:加入厚度與體積函數 (在子物件使用父物件的欄位)
執行結果
s.area() = 0
r.area() = 40
r.volume() = 80
c.area() = 12.5664
c.volume() = 37.6992
c.volume() = 62.832
程式碼
using System;
class Shape
{
public double thick;
public virtual double area() { return 0.0; }
}
class Rectangle : Shape
{
double width, height;
public Rectangle(double w, double h)
{
width = w;
height = h;
thick = 2.0;
}
public override double area()
{
return width * height;
}
public double volume()
{
return width * height * thick;
}
}
class Circle : Shape
{
double r;
public Circle(double r)
{
this.r = r;
thick = 3.0;
}
public override double area()
{
return 3.1416 * r * r;
}
public double volume()
{
return area() * thick;
}
}
class Test
{
public static void Main(string[] args)
{
Shape s = new Shape();
Console.WriteLine("s.area() = " + s.area());
Rectangle r = new Rectangle(5.0, 8.0);
Console.WriteLine("r.area() = " + r.area());
Console.WriteLine("r.volume() = " + r.volume());
Circle c = new Circle(2);
Console.WriteLine("c.area() = " + c.area());
Console.WriteLine("c.volume() = " + c.volume());
c.thick = 5;
Console.WriteLine("c.volume() = " + c.volume());
}
}
範例三:將 volume() 函數提到 Shape 物件中
using System;
class Shape
{
public double thick;
public virtual double area() { return 0.0; }
public double volume()
{
return area() * thick;
}
}
class Rectangle : Shape
{
double width, height;
public Rectangle(double w, double h)
{
width = w;
height = h;
thick = 2.0;
}
public override double area()
{
return width * height;
}
}
class Circle : Shape
{
double r;
public Circle(double r)
{
this.r = r;
thick = 3.0;
}
public override double area()
{
return 3.1416 * r * r;
}
}
class Test
{
public static void Main(string[] args)
{
Shape s = new Shape();
Console.WriteLine("s.area() = " + s.area());
Rectangle r = new Rectangle(5.0, 8.0);
Console.WriteLine("r.area() = " + r.area());
Console.WriteLine("r.volume() = " + r.volume());
Circle c = new Circle(2);
Console.WriteLine("c.area() = " + c.area());
Console.WriteLine("c.volume() = " + c.volume());
c.thick = 5;
Console.WriteLine("c.volume() = " + c.volume());
}
}
文章轉載:陳鍾誠 (2010年10月19日),(網頁標題) C# 與物件導向的繼承 (Inheritance),(網站標題) 免費電子書:C# 程式設計,2010年10月19日,取自 http://cs0.wikidot.com/inheritance ,網頁修改第 5 版。
文章標籤
全站熱搜