Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we are implementing interfaces ?

Tags:

c#

interface

Why are we implementing, for example ICloneable or IDisposable. I'm not asking what ICloneable or IDisposable do, but I want to learn what's a good reason to implement these interfaces rather than just writing a method which disposes or clones our objects?

like image 509
Tarik Avatar asked Oct 18 '09 01:10

Tarik


People also ask

What is an implementation of an interface?

An implementation of an interface is a Java program that references the interface using the implements keyword. The program is required to provide method logic for all non-default methods. Optionally, the program can provide an implementation of a default method defined in the interface.

Do we need to implement all interface?

Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class. Implement every method defined by the interface.

What happens when you implement an interface?

When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. A class uses the implements keyword to implement an interface.


2 Answers

Using interfaces keeps the use of those pieces of functionality consistent. That way, when another class wants to / needs to use your class, it can act on it as a cloneable, disposable object without worrying about your particular implementation details.

like image 91
phoebus Avatar answered Sep 23 '22 08:09

phoebus


By implementing a well known interface, you can have polymorphism, which enable you to write generic code that can act on any instance of a class that implementes a given interface.

You can check the Wikipedia article on polymorphism for more.

like image 26
pgb Avatar answered Sep 23 '22 08:09

pgb