什么是 C# 中的抽象?
抽象和封装是面向对象编程中的相关特性。抽象允许公开相关信息,封装使程序员能够实现所需级别的抽象。
使用 C# 中的抽象类可以实现抽象。C# 允许您创建用来提供接口部分类实现的抽象类。当导出类从中继承时,实现便已完成。抽象类包含抽象方法,由派生类实现。派生类有更专门的功能。
以下是一些重点 −
你无法创建抽象类的实例
你无法在抽象类之外声明抽象方法
当类被声明为 sealed 时,它无法被继承,抽象类不能被声明为 sealed。
示例
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;
}
public override int area () {
Console.WriteLine("Rectangle class area :");
return (width * length);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle r = new Rectangle(20, 15);
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
}输出
Rectangle class area : Area: 300
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP