Finished Defining an Abstract Class, repo at f6215b7

Jason Zhu 2021-02-23 10:19:58 +11:00
parent 93735d8878
commit e532d0b599

@ -80,3 +80,89 @@ Reference:
Abstract class is prerequist of polymorphism
TODO: Understand polymorphism more deeply.
## Defining an Interface
Reference:
* [Very Useful: Interface in C# (dotnettutorial)](https://dotnettutorials.net/lesson/interface-c-sharp/)
* [Very Useful: Multiple Inheritance in C#](https://dotnettutorials.net/lesson/multiple-inheritance-csharp/)
* [Interfaces (C# Programming Guide)](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/)
.NET provides an alternative approach known as the interface to support the concept of **multiple inheritances**, (as .NET does not support by nature)
Interface force the class signatures, while ignoring implementation in details.
### Declare interface
Using `interface` to declare an interface.
```csharp
// SYNTAX:
public interface InterfaceName
{
//only abstract members:
// Abstract methods
// Properties
// Indexes
// Events
}
```
e.g.
```csharp
public interface Example
{
void show();
}
```
### Working with interface
Interface provides a forceful rule for classes to implementation. Hence, multi-inheritance is enabled
```csharp
namespace InterfaceDemo
{
public interface Area
{
void area(double a, double b);
}
class Rectangle : Area
{
public void area(double a, double b)
{
double areaRectangle;
areaRectangle = a * b;
Console.WriteLine("the area of rectangle is :" + areaRectangle);
}
}
class Circle : Area
{
static double PI = 3.14;
public void area(double a, double b)
{
double areaCircle;
areaCircle = PI * a * a;
Console.WriteLine("the area of Circle is :" + areaCircle);
}
}
class Program
{
static void Main(string[] args)
{
Area a = new Rectangle();
a.area(5, 6);
a = new Circle();
a.area(7, 0);
Console.WriteLine("Press any key to exist.");
Console.ReadKey();
}
}
}
```
### Tips
* Naming Convention: Interface is begin by `I`. e.g. `IBook`
* Interfaces are far more commen than abstract class
* When class inherit from interface, methods from interface must be implemented, even if it's abstract class, and implemented methods are virtual