faqts : Computers : Programming : Languages : C#

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

11 of 22 people (50%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

What is an interface? Explain me with example.

Feb 3rd, 2006 11:59
Pravin Paratey, Tony Cruise,


Interfaces are a lot like abstract classes. In fact, an interface is
nothing but an abstract class with only abstract methods in it.
Why are interfaces necessary? Well, they aren't necessary, but they sure
do make programming a lot easier. 
Let's take an example. Say, you have to write a graphics application
that lets the user draw lines, rectangles and ellipses. One way to do
this would be to write different classes to do these figures. Another
way would be to define an interface and have the line, rectangle and
ellipse class derive from it. Like so,
public interface DrawObject
{
	// rect defines the bounding box for the object to be drawn
	public void Draw(RECT rect);
}
public class Line : DrawObject
{
	public void Draw(RECT rect)
	{
		// Code to draw line here
	}
}
public class Rectangle : DrawObject
{
	public void Draw(RECT rect)
	{
		// Code to draw rectangle here
	}
}
This could've been done using a normal class too. So why interface?
Deriving from an interface *forces* you to define the functions within
the interface. This way, you know that everytime you derive from the
interface, you *will* have those functions.
So now, you can have an ArrayList of DrawObjects and just call the
Draw() function on each without bothering about what kind of object it
really is.