This content originally appeared on DEV Community and was authored by △ LUKE知る
Note: We will use a famous example, an Animal, for the whole article
What is Abstract?
Abstract class provide a base define for something (Ex: Base class for Dog and Bird is Animal). It present for Polymorphism in OOP. An abstract class is declared using the abstract
keyword. It can contain both abstract methods (without implementations) and non-abstract methods (with implementations). Take a look at example below
We define abstract class Animal
with the following detail:
- Properties: name
- Abstract methods: MoveBy
- Non-abstract methods: Print
Next, we will create two classes Dog
and Bird
which implement Animal
. After that, we initialize them
Now we can get some point in here:
- Every
Dog
andBird
have the name (1) - But
Dog
move by leg andBird
move by wing (maybe by leg also but assume it) (2)
With (1), we can declare Print
method in Animal
with non-abstract type to use for Dog
and Bird
With (2), the MoveBy
method must be abstract and it would be declared in each class later. This is the key point to show difference between abstract and non-abstract method.
Summary,
-
Abstract
class provide a base definition (Ex: Animal) -
Abstract
method provide base method which execute differently for each class implement (Ex: MoveBy) -
Non-abstract method
are usually use as a common method for all class implementation (Ex: Print)
What is Interface?
For short, an interface
is a completely “abstract class” that defines a contract for related functionalities. When we sign a contract, we must provide/do everything defined in a contract, like A
must give B
100k$ and don't need to know A
give cash or transfer - that is the Abstraction
in OOP. Take a look at the example below
We define interface class IAction
with the following detail:
- Move
- Talk
Next, we will extend two classes Dog
and Bird
, which have been implement Animal
, with IAction
.
We can see in IAction
, we have two methods with abstract types that execute differently in each class.
Summary,
-
Interface
define a contract or set of rules that classes must adhere to. -
Interface
class contains only abstract method, not fields
This content originally appeared on DEV Community and was authored by △ LUKE知る
△ LUKE知る | Sciencx (2024-07-01T21:48:01+00:00) Abstract & Interface in C#. Retrieved from https://www.scien.cx/2024/07/01/abstract-interface-in-c/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.