1

I can declare functions and properties in an interface, but I cannot implement them. When I inherit from the interface, I now have to implement all these members in my class. If I have to do that, what's the point of declaring the interface at all?

For example, here's an example interface:

namespace InterfaceExample
{
    public interface IVehicle
    {
        int Doors { get; set; }
        int Wheels { get; set; }
        Color VehicleColor { get; set; }
        int TopSpeed { get; set; }
        int Cylinders { get; set; }
        int CurrentSpeed { get; }

        string DisplayTopSpeed();
        void Accelerate(int step);
    }
}

I've declared all the properties and functions in this interface. Now, when I use this interface in my class like this:

namespace InterfaceExample
{
    public class Motorcycle : IVehicle
    {
        private int _currentSpeed = 0;

        public int Doors { get; set; }

        public int Wheels { get; set; }

        public Color VehicleColor { get; set; }

        public int TopSpeed { get; set; }

        public int HorsePower { get; set; }

        public int Cylinders { get; set; }

        public int CurrentSpeed
        {
            get { return _currentSpeed; }
        }


        public Motorcycle(int doors, int wheels, Color color, int topSpeed, int horsePower, int cylinders, int currentSpeed)
        {
            this.Doors = doors;
            this.Wheels = wheels;
            this.VehicleColor = color;
            this.TopSpeed = topSpeed;
            this.HorsePower = horsePower;
            this.Cylinders = cylinders;
            this._currentSpeed = currentSpeed;
        }

        public string DisplayTopSpeed()
        {
            return "Top speed is: " + this.TopSpeed;
        }

        public void Accelerate(int step)
        {
            this._currentSpeed += step;
        }
    }

I have to declare all the properties again.

So why bother at all with the interface in the first place? It seems like a waste of time, since I will be implementing all the members in my class anyhow.

Superbest
  • 25,318
  • 14
  • 62
  • 134
Azad Chouhan
  • 277
  • 1
  • 6
  • 18
  • As an example, consider the fact that the DataSource property of a DataGridView will only accept an object that implements the IList or IListSource interface. It doesn't care what the object is or how it is implemented because as long as it implements one of those interfaces then it knows how to get data out of and into that data source. Without those interfaces, how would you bind data to a grid? It would have no idea how to get the data in or out so it would be useless. The interface makes binding possible but it's completely up to you how the class implements the interface. – jmcilhinney Jan 21 '14 at 06:18
  • Related: http://stackoverflow.com/questions/761194/interface-vs-abstract-class-general-oo?rq=1 – Excelcius Jan 21 '14 at 06:20
  • 1
    @mainrajput you should take a look at `design patterns.` And `polymorphism` – Selman Genç Jan 21 '14 at 06:27
  • New developers often get the wrong idea about interfaces and think that every class they create should have a backing interface and think, like you I believe, "That sounds crazy" You are right. That would be crazy. Use interfaces only where it makes sense to have them, otherwise you are just cluttering your code. They do serve an important purpose but like anything, they can and are frequently overused. – Echostorm Jan 09 '23 at 19:55

6 Answers6

9

As other answers emphasize interfaces tell you what to do and how to do is up to you to implement.

1. Then why I waste my time in create a Interface If I have to declare all the properties and functions of My Interface in my class.

Ok. You are creating a Motorcycle and by implementing the interface IVehicle, the MotorCycle class is forced to implement all the members of the interface IVehicle.

If you had not used an interface called IVehicle, you might actually forget to implement something that you should have been implemented.

Tomorrow, if somebody wants to build a Car then you can implement from IVehicle, people can implement all its methods and customize.

The purpose of the IVehicle interface is to make sure that whenever you build a vehicle class, it reminds and forces you to make sure that you rightly build a vehicle

2. For Properties, interface is a waste of time ?

No and definitely not.

For example, whenever you want to return the vehicle speed, instead of just rounding of the vehicle speed to integer you want in exact floating point,

10 // public float currentSpeed { get; set; }

10.5 // public float currentSpeed { get {return {//write custom logic}; set; }

Notice the customisation in Get accessor of the property.

3. When should abstract class be used ?

Abstract class should be used when all derived class would be using some repeated method. For example,

public abstract Class AbstractClass
{
        public virtual int Doors { get; set; }

        public virtual int Wheels { get; set; }

        public virtual Color VehicleColor { get; set; }

        public virtual int TopSpeed { get; set; }

        public virtual int HorsePower { get; set; }

        public virtual int Cylinders { get; set; }

        public string WhatSideDriving
        {
           if (Country == "US") return "Keep Right";
           if (Country == "India") return "Keep Left";
        }

}

Do note that the method WhatSideDriving is already implemented and can be used by all the classes that derive from this class. However other members can be overridden and can be implemented according to the required functionality.

  • kk then what about abstract classes and functions that are also same but we can't define anything in that then what is the use of abstract class?? – Azad Chouhan Jan 21 '14 at 06:30
  • @mainrajput You can implement functions in abstract classes, you just can't do it in interfaces. Have a look at the related links, there are many explainations for the differences between interface and abstract class. – Excelcius Jan 21 '14 at 06:31
  • `abstract classes` are used for different purpose. For example, `in interface, all members should be just declared.` but `in abstract class, it is a mix. You would be having declaration as well as implementation` – now he who must not be named. Jan 21 '14 at 06:32
  • thanks sir you really give me my answer related to this interesting topic I google this alot for this topic but nothing can give me satisfied answer but it is really a nice way of explanation I know how to implement interfaces but I did not get any solid reason why to use Interface and You tell me today thanks :) – Azad Chouhan Jan 21 '14 at 06:35
  • 2
    @mainrajput: Cool. Glad it helped. I have also replied on `a use-case of abstract class with your scenario`. And one more note: Do listen to other people's answers too, Just research and understand patiently. You will grow. – now he who must not be named. Jan 21 '14 at 06:40
6

Then why I waste my time in create a Interface If I have to declare all the properties and functions of My Interface in my class.

Because an interface is just that; a (public) interface. It does not define an implementation, only the methods and properties used to interface to any of its implementations.

Of course, implementors of said interface must define the implementation of it. How else would you expect this to work?

That said, it's not inconceivable that properties could be implicitly (and invisibly) implemented as automatic properties, but that doesn't work for methods, and you often need more than get; set; anyway, so it would provide little benefit (i.e., a feature that isn't worth the effort).

Ed S.
  • 122,712
  • 22
  • 185
  • 265
  • No I have a question in my mind from many days that Why I use interface If I have to declare all the properties again in my class is it not double my work???? – Azad Chouhan Jan 21 '14 at 06:13
  • Well he's got a point - when it comes to simple properties, it would be nice to be able to auto-generate those. But yes, the whole use of interfaces is to provide a user-defines implementation to a common interface. – Excelcius Jan 21 '14 at 06:13
  • 1
    @Excelcius: I gave my opinion on that one. C# could do that, but the benefit would be small and likely not worth the time. – Ed S. Jan 21 '14 at 06:14
  • @mainrajput: Yes, that's what you said, and I believe I have provided an answer. – Ed S. Jan 21 '14 at 06:14
  • @EdS Yeah, posted the comment before the edit ;) – Excelcius Jan 21 '14 at 06:14
  • @Excelcius: Yeah, I was a bit slow with that part. – Ed S. Jan 21 '14 at 06:20
5

Strictly speaking, declaring an interface is a waste of time. You could skip the interface and save some time.

However, you would be cutting the wrong corner. While it's a bit of extra time and work, in the long run interfaces are invaluable. One of the marks of a truly great software engineer is being able to design interfaces well.

To be less abstract, the interface is designed for precisely that purpose: To formalize the interface between two kinds of classes (in other words, how the two classes work together). It is a bit like a contract between classes, where each class says what they promise to provide and what they will expect. Your IVehicle example, for instance, vows that it will always have a property called doors. Then, any code which works with IVehicle can trust all implementations of IVehicle to always have a Doors. You can now safely write code which accesses IVehicle.Doors knowing that no matter what particular implementation happens to get passed to this method, your code will definitely work - even if the Vehicles package developer decides to one day add some vehicles you've never heard about or considered!

When you have only one small class implementing the interface, and you are the only developer, interfaces may be superfluous. However, what if there were multiple kinds of vehicles, each with their own logic and different members, which must nevertheless be used by some general code? For example, a vehicle tracking manager must handle classes Car, Truck, Plane and so on. Why not? They all have a speed and position, and that's all that matters.

Moreover, when you let other developers write their own vehicles, the interface is a great way of showing them how they must do this for it to work with the rest of your code.

Likewise, when you work on a large project, and split each part between different developers, well-designed interfaces can ensure that these programmers, working on different parts of the project in relative isolation, will still create a whole which works thanks to parts that fit together nicely.

Similarly, a good interface is a great way to start a complicated class even when coding on your own: It will help you keep track of what you need to implement and how, but unlike a more familiar technical specification, an interface can be understood by the compiler so that it can assist you in many ways (such as help from IntelliSense when you want to write logic using parts of your class that you will implement later).

In C# particularly, interfaces also have a practical benefit. You can't inherit from more than one class or abstract class in C# (unlike C++). This is done because multiple inheritance turns out to make life very difficult for programmers sometimes. But you can inherit from multiple interfaces, and because they are only interfaces (with no implementation) the "multiple inheritance" thing is much less of an issue.

Lastly, a real world example: Microsoft has provided for you a List.Sort method which will helpfully sort a list of any object. It is obviously easy to do this for things like numbers and strings, but it is possible to make it sort arbitrary objects you made, like vehicles. But how could Microsoft possibly know what kinds of classes you will implement, and how you intend for these to be sorted? They don't, but they provide for you an interface called IComparable. This defines the methods that sorting code needs to call to be able to compare two objects for sorting. If the object you put into your list implements this IComparable, you will have told Microsoft's List.Sort code how your objects should be sorted, and now you no longer have to write your own sort function since you can just use the well designed, tested, documented and debugged Microsoft one.

As an exercise, try writing a program which takes a list of Triangle classes (which have only a, b, c fields that store the length of each side, and a CalculateArea method) and then sorts it by area using Microsoft's List.Sort. Don't write your own sorting code, and don't use thing like LINQ OrderBy, instead do it by making Triangle implement IComparable. Then think about this: If you were the project manager in charge of development of all the .NET libraries, how would you write a sort function that anyone can use, even with their own weird classes?

Superbest
  • 25,318
  • 14
  • 62
  • 134
1

You create an interface if you need to create an interface.

You can pass all types of vehicles as the interface type to methods. If you declare all three of the following and you need to calculate their fuel efficiency, you would need three separate methods that do that.

example:

public class Truck {}

public class Car {}

public class Motorcycle {}

With an interface you need one method:

public int GetFuelEfficiency(IVehicle vehicle)

The interface requires you or anyone else implementing it to declare ALL of its properties and methods. This way all classes implementing the interface will contain all the necessary properties and methods to be treated by other code in the same manner regardless of the classes specific implementations.

There are yet other reasons for declaring an interface like the lack of multiple inheritance in C#, etc.

Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
0

Interfaces are definitions, and not implementations. Classes are both implementations and definitions.

The point of an interface is to separate implementation from definition, so that that the consumer does not have any knowledge of the actual object used to implement the interface.

Yes, it's more work, but good design is always more work than bad.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
  • oh my god I am still not getting my answer why I use interface If i have to declare all the properties of Interface again in my class???? – Azad Chouhan Jan 21 '14 at 06:18
  • @mainrajput: You got your answer, you just refuse to accept it or don't understand it. Which is it? Tell me; how should your class magically implement the interface method `int Foo();`? – Ed S. Jan 21 '14 at 06:20
  • 2
    @mainrajput - That's because you're not listening. – Erik Funkenbusch Jan 21 '14 at 06:20
  • Perhaps he is really looking for an explanation of the uses and benefits of using interfaces to abstract away implementations. Too bad I have a crying baby to deal with... – Ed S. Jan 21 '14 at 06:24
  • Let me clear it I declare a function in a interface Inter with a name A(); Now I Implements the Interface in myclass abc. Now in this Class I have to declare A(); Again with Implementation Now Why I declare A(); In Interface If I have to Declare it in my class again with implementation @MystereMan – Azad Chouhan Jan 21 '14 at 06:27
  • Since properties _can_ be used to declare variables, the difference between an abstract baseclass and an interface might not be clear to someone implementing an interface with properties only. But as soon as you start declaring methods in an interface or know that properties are actually just get/set methods, the use becomes apparent. – Excelcius Jan 21 '14 at 06:27
0

Interface provides a blueprint for implementation. You have the freedom to create the actual class from that blueprint. To be able to do so, you have to define all the aspects of that blueprint.

Interface is mostly used to create pluggable interfaces to applications and are also used to support multiple inheritance.

References:

You may also use Abstract classes if it suits your purpose. But Abstract class != Interface.

Vivek Jain
  • 3,811
  • 6
  • 30
  • 47