- Hands-On Object:Oriented Programming with C#
- Raihan Taher
- 254字
- 2021-07-02 12:44:43
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
}
}
- Android Wearable Programming
- Selenium Design Patterns and Best Practices
- Java加密與解密的藝術(第2版)
- R語言編程指南
- Python王者歸來
- Java編程技術與項目實戰(第2版)
- Responsive Web Design by Example
- Mastering Data Mining with Python:Find patterns hidden in your data
- JavaScript從入門到精通(視頻實戰版)
- Android編程權威指南(第4版)
- Splunk Essentials
- 計算機程序的構造和解釋(JavaScript版)
- Clojure Data Structures and Algorithms Cookbook
- 匯編語言程序設計
- 軟件定義存儲:原理、實踐與生態