?
Solved

Interfaces in C#

Posted on 2006-05-23
8
Medium Priority
?
282 Views
Last Modified: 2010-04-16
Hi,

Can somebody tell me please... What is the advantage of using an interface when the class that implements the interface has to have implemented every method described by the interface?  Why not just extend that class to contain the methods in the interface, then delete the interface..?

Thanks.
0
Comment
Question by:sublimation
  • 6
  • 2
8 Comments
 
LVL 6

Expert Comment

by:PoeticAudio
ID: 16746238
Because an interface allows you to do stuff like this....(psuedocode)

IAppliance fridge = new Fridge();  //the Fridge object implements IAppliance
TurnOnAppliance(fridge);

IAppliance washMachine = new WashingMachine();
TurnOnAppliance(washMachine);   //calling the same method, and it will work!

private void TurnOnAppliance(IAppliance appliance)
{
    appliance.TurnOn();
}

notice that the TurnOnAppliance doesn't care which appliance it is, as long as it implements IAppliance then it knows that it can call the TurnOn() method. Of coarse this is assuming that there is a TurnOn() method defined in the IAppliance interface.

it lets you abstract your objects out. You can do the same thing with inheritance, but since C# doesn't support multiple inheritance if you're already ineriting from another object then you can still get the benefit of using that object like you can with multiple inheritance
0
 
LVL 6

Expert Comment

by:PoeticAudio
ID: 16746290
If you did it your way and then removed the interface you couldn't do that. You would have to do something like

Fridge fridge = new Fridge();
TurnOnFridge(fridge);

WashingMaching washMachine = new WashingMachine();
TurnOnWashingMachine(washMachine);

private void TurnOnFridge(Fridge fridge)
{
    fridge.TurnOn();
}

private void TurnOnWashingMachine(WashingMachine wMachine)
{
     wMachine.TurnOn();
}

notice with each new object, if they don't implement an interface (or are derrived from a common base class) then either you're going to have to do a bunch of if-then logic, or your going to have to write methods specific to each object. With interfaces, we don't have to do that as illustrated above. Derriving from a base class can do the same thing (as I said earlier) but sometimes you don't want to derrive from a base class, or sometimes you already are derriving from a base class so you have to implement an interface if you want to use OOP techniques like I showed you previously.

On a final note, if you derrive from a base class you can think "objectA IS an objectB" but with an interface you should design it so "objectA acts like objectB"
0
 
LVL 4

Author Comment

by:sublimation
ID: 16747272
Nearly understand it.  What if we had a Comic class and a Bible class.  They both inherit the Display class so can use its Print method...So the Comic and Bible class can print without having to have their own print code within their classes.  It seems to me that with interfaces, one still has to put in all the code for the Print method within the Bible and Comic class SEPERATELY and the Interface has just A decared method called Print but no code do do the printing...  
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 6

Accepted Solution

by:
PoeticAudio earned 2000 total points
ID: 16748227
I think you're not fully understanding the benefits of interfaces, but that's okay, they aren't easy to fully grasp right away.

In that case with the comic and the bible class a print method like you're saying would belong in a base class so you could have implementation in both classes when you derrive from the base class.

The purpose of an interface is not to implement code at all. The purpose of an interface is so that object that implements it has a contract that says it MUST implement certain methods. This is handy because since the object is bound by that interface, other objects know which methods that the objects that implement that interface must contain, therefor it can call methods on that object without knowing anything else about it. This allows for a plug-n-play type architecture. Once you become more advanced in OOP design then it will make much more sense to you.

Remember, we aren't using interfaces to save us coding by having implementation in a base class, that's what base classes are for. We are allowing other objects to know a little bit about the object that implementation such as which methods it contains that way the object can call those methods without knowing anything else. Interfaces aid in keeping your objects loosely coupled. The looser your objects are coupled with eachother, the less they know about eachother which helps you build flexible, reusable classes. Interfaces are used for designing systems with loosely coupled objects that can allow for a plug-n-play type architecture like I mentioned earlier... this becomes a HUGE benefit as you learn how to model your software architecture.

Here is a little more about interfaces... probably more understandable then I am =)


http://www.google.com/search?hl=en&q=programming+understanding+interfaces
0
 
LVL 6

Expert Comment

by:PoeticAudio
ID: 16748235
OOPS!!! This is the link I meant to post =) I accidently gave you the google search I used to find it... sorry! =)

http://www.csharp-station.com/Tutorials/Lesson13.aspx
0
 
LVL 6

Expert Comment

by:PoeticAudio
ID: 16748558
One quick thing...

The sample that I provided you earlier with the WashingMachine is a little misleading. It implements the IAppliance interface when actually it would be better to have an Appliance base class. Interfaces are more handy when used like IDisposable in visual studio. Any object that implements the IDisposable interface must have a Dispose method, which means that with any object that implements IDisposable we are guaranteed that the object has a Dispose method, so no matter which object it is... if it implements IDisposable we know we can call Dispose on it without knowing anything else about the object. Perhaps the WashingMachine would derrive from Appliance, but have an IElectrical interface which would have the method PlugIn(); So no matter which Appliance (or anything else that is electrical, not even Appliance objects but other objects such as Radios, or TVs) has IElectrical is guaranteed to have a PlugIn() method, no matter what. This may be handy because Appliances might plug into a certain socket, but TVs plug into a different type of socket, or appliances in a different country might yet have a different type of socket to plug into. We dont really care about that, we just care that it can plug into something electrical because it has IElectrical.

So we could have WashingMachine which is derrived from Appliance, so it can do anything a basic appliance can do at it's most basic level such as TurnOn, TurnOff...etc, but also the WashingMachine implements IElectrical so we know that we can plug it in.


 interface IElectrical
{
    void PlugIn();
}

public class WashingMachine : Appliance, IElectrical
{
    public void PlugIn()
    {
        System.Windows.Forms.MessageBox.Show("i'm plugged in!");
    }
   
    public override void TurnOn()
    {
        System.Windows.Forms.MessageBox.Show("I'm on!");
    }
}


Now say we have a 3 prong adapter that you would use so you can plug in a 3 prong plug into a 2 prong outlet, you know. It's an electrical component because it transfers electricity, but it's not an appliance, it's just a 3 prong adapter

public class ThreeProngAdapter, IElectrical
{
    public void PlugIn()
    {
        System.Windows.Forms.MessageBox.Show("I'm plugged in. Now you can plug a 3 prong cord into " +
            "this two prong outlet");
    }
}


So we have a WashingMachine and a ThreeProngAdapter. They are completely different in what they do. A WashingMachine, well washes clothes and such, but a ThreeProngAdapter doesn't. It just makes it so you can plug a 3 prong cord into a 2 prong outlet, but we can still do this...

WashingMachine wm = new WashingMachine();
PlugInComponent(wm);

ThreeProngAdapter tpa = new ThreeProngAdapter();
PlugInComponent(tpa);

private void PlugInComponent(IElectrical electricalComponent)
{
    electricalComponent.PlugIn();
}


notice that we can still run the same method on the washing machien and the adapter because they both use IElectrical. The adapter doesn't derrive from Appliance because we don't want a TurnOn() method for it, you don't really turn the adapter on. You can create some neat designs by using interfaces because two totally different types of objects can be used in the same way in certain circumstances, for example the adapter and the washing machine were both able to be passed through the PlugInComponent method despite those objects having nothing else in common. The PlugInComponent method doesn't care at all if it's an appliance, a three prong adapter, speaker wire... as long as it has IElectrical it knows that it must have a PlugIn(); method, so we're able to call it and the object that implements the PlugIn method takes care of the rest.
0
 
LVL 6

Expert Comment

by:PoeticAudio
ID: 16748570
TYPO!!!

Sorry wasn't really paying much attention when I wrote the last post I guess...

public class ThreeProngAdapter, IElectrical

should be

public class ThreeProngAdapter: IElectrical

(no comma, in the second one)

guess i'm getting tired =)
0
 
LVL 4

Author Comment

by:sublimation
ID: 16749681
Thanks, mate!
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
High user turnover can cause old/redundant user data to consume valuable space. UserResourceCleanup was developed to address this by automatically deleting user folders when the user account is deleted.
Integration Management Part 2
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
Suggested Courses
Course of the Month14 days, 1 hour left to enroll

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question