- Hands-On Object:Oriented Programming with C#
- Raihan Taher
- 356字
- 2021-07-02 12:44:43
Interfaces
A class is a blueprint, which means it contains the members and methods that the instantiated objects will have. An interface can also be categorized as a blueprint, but unlike a class, an interface doesn't have any method implementation. Interfaces are more like a guideline for classes that implement the interface.
The main features of interfaces in C# are as follows:
- Interfaces can't have a method body; they can only have the method signature.
- Interfaces can have methods, properties, events, and indexes.
- An interface can't be instantiated, so no object of an interface can be created.
- One class can extend multiple interfaces.
One of the major uses of an interface is dependency injection. By using interfaces, you can reduce the dependencies in a system. Let's look at an example of an interface:
interface IBankAccount {
void Debit(double amount);
void Credit(double amount);
}
class BankAccount : IBankAccount {
public void Debit(double amount){
Console.WriteLine($"${amount} has been debited from your account!");
}
public void Credit(double amount){
Console.WriteLine($"${amount} has been credited to your account!");
}
}
In the preceding example, we can see that we have one interface, called IBankAccount, that has two members: Debit and Credit. Both of these methods have no implementations in the interface. In the interface, the method signatures are more like guidelines or requirements for the classes that will implement this interface. If any class implements this interface, then the class has to implement the method body. This is a great use of the OOP concept of inheritance. The class will have to give an implementation of the methods that are mentioned in the interface. If the class doesn't implement any of the methods of the interface, the compiler will throw an error that the class has not implemented all the methods of the interface. By language design, if an interface is implemented by a class, all the members of the interface must be taken care of in the class. Consequently, in the preceding code, the BankAccount class has implemented the IBankAccount interface and this is why the two methods, Debit and Credit, have to be implemented.
- Raspberry Pi for Python Programmers Cookbook(Second Edition)
- 計算思維與算法入門
- SOA實(shí)踐
- GraphQL學(xué)習(xí)指南
- iOS 9 Game Development Essentials
- Flask Web開發(fā)入門、進(jìn)階與實(shí)戰(zhàn)
- 營銷數(shù)據(jù)科學(xué):用R和Python進(jìn)行預(yù)測分析的建模技術(shù)
- 匯編語言程序設(shè)計(第3版)
- WordPress Plugin Development Cookbook(Second Edition)
- Building an RPG with Unity 2018
- 劍指Java:核心原理與應(yīng)用實(shí)踐
- ANSYS Fluent 二次開發(fā)指南
- Unity 2D Game Development Cookbook
- Node Cookbook(Second Edition)
- Visualforce Developer’s guide