Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

why use interfaces?

Status
Not open for further replies.

progressdll

Programmer
Feb 28, 2002
41
BE
why use interfaces?

Trying to understand C#, i came across interfaces.
But i don't grasp to idea.

First, what do i know about them.

in an interface you describe methods. But do not implement them.
Then when you create a new class. You use the interface to inherit
it in the new class.

But why would you not create a new class and describe and implement
the methods there. You need to write the code for the methods anyway
because there is no code in the interface. What would be the point
in using them?

Joeri
 
It's about consistency.

Say I have many objects that each need to be able to do similar functionality but each will do it differently. If I create an interface and then implement it in all the appropriate classes, a developer using the classes can be sure of what methods my classes will provide and the signatures for those methods. Makes programming to the classes a lot easier.

Craig
 
as i understand it an interface is not an object, it is a contract. i can see how different objects can be created utilizing the same interface, but i do not see how polymorphism applies to this.

isn't polymorphism an instance where a class is derived from a base class and then overrides existing methods / adds new methods for modified state and action? from my limited understanding of interfaces, do they even allow modifications from the defined contract? i know you can implement multiple interfaces to further define a classes activity, but if it does allow modifications to the core contract ~ i am unaware of it. in that sense i do not see polymorphism at work.
 
hmmm, as i was reading my own reply i began to realize that a method defined by an interface acts the same way as a ovverridable method of a class, except you really do not have an option to override or not.

this is, from my understand, exactly what polymorphism is.
 
however, last post ;), i do believe that interfaces are not required to perform polymorphism. you could perform polymorphism from class inheritance if the class allows.
 
Correct. Polymorphism can be done either through inheritance or interfaces... or both. A class can implement multiple interfaces, but can only inherit from one parent class.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top