什麼是 C# 中的抽象類?
抽象類包含抽象方法,由派生類實現。派生類具有更加專門的功能。
以下是一個示例,展示了在 C# 中使用抽象類。
示例
using System;
namespace Demo {
abstract class Shape {
public abstract int area();
}
class Rectangle: Shape {
private int length;
private int width;
public Rectangle( int a = 0, int b = 0) {
length = a;
width = b;
Console.WriteLine("Length of Rectangle: "+length);
Console.WriteLine("Width of Rectangle: "+width);
}
public override int area () {
return (width * length);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle r = new Rectangle(14, 8);
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
}輸出
Length of Rectangle: 14 Width of Rectangle: 8 Area: 112
我們的抽象類為 -
abstract class Shape {
public abstract int area();
}以下是有關於抽象類的規則。
- 不能建立抽象類的例項
- 不能在抽象類之外宣告抽象方法
- 當一個類被宣告為 sealed,它就不能再被繼承,而抽象類不能被宣告為 sealed。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP