官术网_书友最值得收藏!

The abstract class

An abstract class is a special kind of class that comes with the C# programming language. This class has similar functionalities to an interface. For example, an abstract class can have methods without implementation and with implementation. Consequently, when a class implements an abstract class, the class has to override the abstract methods of the abstract class. One of the main characteristics of an abstract class is that it can't be instantiated. An abstract class can only be used for inheritance. It might or might not have abstract methods and assessors. Sealed and abstract modifiers can't be placed in the same class, as they have completely separate meanings.

Let's take a look at an example of an abstract class:

abstract class Animal {
public string name;
public int ageInMonths;
public abstract void Move();
public void Eat(){
Console.WriteLine("Eating");
}
}
class Dog : Animal {
public override void Move() {
Console.WriteLine("Moving");
}
}

In the preceding example, we saw that the Dog class is implementing the Animal class, and as the Animal class has an abstract method called Move(), the Dog class must override it.

If we try to instantiate the abstract class, the compiler will throw an error, as follows:

using System;
namespace AnimalProject {
abstract class Animal {
public string name;
public int ageInMonths;
public abstract void Move();
public void Eat(){
Console.WriteLine("Eating");
}
}
static void Main(){
Animal animal = new Animal(); // Not possible as the Animal class is abstract class
    }
}
主站蜘蛛池模板: 光山县| 麦盖提县| 望都县| 安西县| 洛扎县| 瑞丽市| 珲春市| 浑源县| 客服| 大渡口区| 波密县| 浑源县| 云浮市| 岳池县| 东城区| 阳东县| 炎陵县| 乌兰察布市| 阳江市| 安庆市| 崇明县| 尖扎县| 桦南县| 阿合奇县| 清新县| 西畴县| 新化县| 宜章县| 鄂伦春自治旗| 万荣县| 江永县| 承德市| 茂名市| 张家口市| 从江县| 灵丘县| 永仁县| 辉南县| 云梦县| 清流县| 格尔木市|