What is the purpose of Interface

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Dear Friends
Please tell me following thing
Que -: what is the main use of interface in .net
Que -: What is difference between abstract class and interface
Que -: How to make class in Object Oriented Form? (in c#

Please mail me at my mail id - (e-mail address removed)
 
Dear Friends ,
Please tell me following thing -
Que -: what is the main use of interface in .net ?

Interfaces are used to pass objects that are completely different but who all have some methods that are defined in the interface.

Consider a class Rock and a class House. Completely different, and nothing in common, almost. For instance, they both can drop down and crash, say in case of an earthquake :P. Now, you have a class Earthquake with a SmashObjects method. Instead of having to create a parent class for everything on earth that can drop, and have every class, like Rock and House inherit that class, you can make an interface IDroppable and have Rock and House implement that interface. In the interface you define Drop(); and now SmashObject can smash every object that implements IDroppable because it knows, no matter how different, they all have a Drop method.

interface IDroppable
{
Drop();
}

class House : IDroppable
{
Drop()
{
// do house dropping stuff
}
}

class Rock : Lava, IDroppable
{
Drop()
{
// do rock dropping stuff
}
}

class Earthquake
{
SmashObjects(IDroppable thingy)
{
thingy.Drop();
}
}

Now, in this sample you could have accomplished the same by making a base parent class and overriding the Drop method, but what if the earthquake wants to roll something. Now, the rock can roll, but not the house (not really), but a car can roll. So, make a new interface IRollable and have the rock and car implement that interface. You can only inherit a single class, but implement numerous interfaces. So basically, what I am trying to safe, interfaces describe some common abilities. Oh, and the I in front of interfaces is intentional to distinguish them from inherited classes.
Que -: What is difference between abstract class and interface?

An abstract class is a blueprint for a new class, it will act in a similar way as a single interface, but as mentioned above, you can only inherit one class, and I find interfaces to be cleaner and easier to maintain.
Que -: How to make class in Object Oriented Form? (in c#)

Eh? Like this?

class MyForm : System.Windows.Forms.Form
{
MyForm()
{
}
}
Please mail me at my mail id - (e-mail address removed)
No can do, I'm writing this over nntp at the moment, without smtp abilities. Maybe someone can forward it.


Happy coding!
Morten Wennevik [C# MVP]
 
Interfaces are used to pass objects that are completely different but who
all have some methods that are defined in the interface.

Thanks for en some simple but excellent examples.

Anders
 
Back
Top