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

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
    }
}
主站蜘蛛池模板: 蒙山县| 潜江市| 宁安市| 广安市| 乐陵市| 资源县| 梅河口市| 安多县| 砚山县| 楚雄市| 江西省| 韶山市| 广宁县| 武冈市| 贵阳市| 虹口区| 海阳市| 若尔盖县| 临清市| 尚志市| 郧西县| 安顺市| 子洲县| 丰镇市| 佛山市| 沂水县| 和平县| 文昌市| 湟中县| 望城县| 炉霍县| 渝北区| 湘潭市| 锡林浩特市| 收藏| 扶风县| 洛隆县| 廊坊市| 云霄县| 七台河市| 泽库县|