0

I am studying the interfaces and have come to know that we can not create instace of the interface.I have gone through numbers of questions that has been already asked at stackoverflow but I am rather expecting something more basic to all of them as my state of mind says.

So as I have done this example which is working very fine where I am implementing a interface implicitly and using the method as if the method is of class itself.

namespace MyConsoleProject
{
    class Program : Iinterface
    {
        public int myfunc(int a, int b)
        {
            return a * b;
        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            int result = obj.myfunc(10, 20);
            Console.WriteLine(result);
            Console.ReadLine();

        }
    }

    interface Iinterface
    {
        int myfunc(int a, int b);
    }
}

I am alright with this but see the way I am calling the interface. I created an instance of class and called the function of interface. First I am not clear with the thing that I am calling the interface method or the class method. As the class have the same method and body. Why do I need Interface then.

The most important one which I come through is:: When I will have need to create instance of interface like this?

Iinterface objinterface=new Program ();
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
Sweetie
  • 1,298
  • 6
  • 24
  • 48
  • This will help you - http://stackoverflow.com/questions/16832280/why-we-do-create-object-instance-from-interface-instead-of-class – MusicLovingIndianGirl Mar 06 '14 at 05:13
  • 1
    This is what we call as abstraction. The caller does not need to know what are all the derived classes available. Say I have IPerson inherited by Employee , User and Guest. These classes may not be needed for caller. He can access all these via interfaces. So, whenever a new class is introduced, there will not much change to caller. We call it as Facade. – Dhanasekar Murugesan Mar 06 '14 at 05:13
  • I've edited the tags for you; removed irrelevant tags and added relevant. – Sriram Sakthivel Mar 06 '14 at 05:13

7 Answers7

2

Let's say you have these classes and an interface:

public interface IDoesSound {
  void Sound();
}

public class Dog : IDoesSound {
  public void Sound() {
    Console.WriteLine("Dog goes Woof!");
  }
}

public class Cat : IDoesSound {
  public void Sound() {
    Console.WriteLine("Cat goes Mew!");
  }
}

And this Main():

static void Main(string[] args) {
  IDoesSound animal = new Cat(); // animal is an instance of Cat
  animal.Sound(); // output: Cat goes Mew!
}

IDoesSound animal guarantees to the compiler that the object assigned to animal will have all the methods and properties declared in IDoesSound, in this case just void Sound(). Because of this, nothing would stop us from having IDoesSound animal = new Dog().

Also, in the Main(), whenever I call animal.Sound(), I am not calling IDoesSound.Sound(), but Cat.Sound(). All the interface does is guarantee that it has the methods and properties in IDoesSound. Another way to put this is that by having class Dog : IDoesSound, Dog is promising to fulfill the contract specified by IDoesSound.

In a more practical example, let's say you want to average a collection of numbers. You put the code in a method Average(). Think about this one - which would be better to have as your parameter to get those numbers, Average(List<double>) or Average(ICollection<double>)? Let's look at reasonable implementations of both.

public static double Average(List<double> numbers) {
  var workingSum = 0.0;
  foreach (var num in numbers) {
    workingSum += num; 
  }
  return workingSum / numbers.Count; 
}

public static double Average(IEnumerable<double> numbers) {
  int count = 0;
  var workingSum = 0.0;
  foreach (var num in numbers) {
    count++;
    workingSum += num; 
  }
  return workingSum / count;
}

With Average(List<double>), I have no choice to call it with a List<double> or derivative as the parameter. I can collect doubles from other collections and use or write code to convert them, true, but with Average(IEnumerable<double>), I do not have to worry about it, as long as the parameter implements IEnumerable<T>.

Consequently, interfaces are a big part of what makes LINQ work, and this whole example can be drilled down to (which nothing but the .NET Framework):

IEnumerable<double> doubles = // get doubles from somewhere
var average = doubles.Average();
jdphenix
  • 15,022
  • 3
  • 41
  • 74
1

Just be aware that you cannot create an instance of an interface. Only an object that implements it.

If you create an object like that, objinterface will only ever have the properties and methods exposed by the interface. You cannot use the rest unless you cast it.

I have found this useful is 2 ways:

1) You use the interface to define somewhat of an contract that you want the object to fulfill

2) You want to restrict the external use of the object and thus use it as a parameter like this. THis also allows for any object that implements the interface to be passed in:

public void MyMethod(Iinterface obj)

or when passing an obj out like this

public Iinterface MyMethod()

this way you can restrict the use of what you are passing out (somewhat).

David Pilkington
  • 13,528
  • 3
  • 41
  • 73
1

I give an example of real word to explain mean of interfaces: interfaces are like our image of a reality, but everyone has himself/herself image of that reality and all images are true! That reality has many dimensions but everyone realizes some of these dimensions.

Merta
  • 965
  • 1
  • 11
  • 23
1

-> First I am not clear with the thing that I am calling the interface method or the class method.

You are calling the class method. You cannot call the interface method. In fact, the interface does not have the method, but just a prototype of it (that is, the definition only).

To be precise, you're calling neither. You are calling the method of the obj instance of the Program class. To call the method of the class directly like Program.myfunc(10, 20), you will need to make the method static.

-> Why do I need Interface then.

You're code here is very simple, so you cannot see the benefit of the interface. Classes seldom match their interfaces like you did. Classes usually have more functionality than the interface. So the interface kind of defines the minimum functionality that the class must have (i.e. implement).

To use simple wording (although not perfectly correct), you use the interface to define a common (that is, shared) functionality among several classes/objects. This makes dealing with those objects much easier without the need to know which object you're dealing with.

For example, le's say you're creating a game with several weapons. You can create IWeapon interface that has the Speed and Strength members as well as the Vibrate method. Each of your weapons classes will have many more members and methods, but they all must have the Speed and Strength members as well as the Vibrate method. So if you have some code that deals with some weapons (that is, instances of the weapons classes) that one of the characters has and you only need to access the common functionality (defined by the interface) of those weapons, you don't need to know what type of weapon you're dealing with. Let's say the character entered a room with some heavy gas that reduces the speed and strength of all weapons by 10% and causes them to vibrate a little, you can right some code like this:

foreach(IWeapon w in myCharacter.Weapons) {
  w.Speed = w.Speed * 0.9;
  w.Strength = w.Strength * 0.9;
  w.Vibrate();
}

-> When I will have need to create instance of interface like this?

-> Iinterface objinterface=new Program ();

This kind of code is useful when all you need is to access the common functionality defined by the interface and you don't need to access the extra functionality of the object defined by the class. This is especially useful when you are building generic functions that operate on all objects of classes that implement the interface. For example, let's say you want to put the code above in a function that is a method of the gas room:

public class GasRoom {
  public void ApplyGasEffect(IList<IWeapon> weapons) {
    foreach(IWeapon w in weapons) {
      w.Speed = w.Speed * 0.9;
      w.Strength = w.Strength * 0.9;
      w.Vibrate();
    }
  }
}

Notice the parameter type IList<IWeapon>. Now you can pass a list of all weapons that my character has to this function like this:

myGasRoom.ApplyGasEffect(myCharacter.Weapons)

And let's say you want to initially give the player two weapons when they start the stage, and then the player enters the gas room, now your line of code comes in handy:

//Give the player two weapons to start with.
myCharacter.Weapons = new List<IWeapons>();
IWeapon b = new Bazooka();
myCharacter.Weapons.Add(w);
IWeapon r = new Rocket();
myCharacter.Weapons.Add(r);
//Or you can do it all in one line like this:
//myCharacter.Weapons = new List<IWeapons>() { new Bazooka(), new Rocket() };

//////// Here goes some other code for the game //////
//////// until the player enters the gas room ////////

myGasRoom.ApplyGasEffect(myCharacter.Weapons)
Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
0

We do not create instances of interface. You are still creating instance of the class here. Interfaces merely provide a declaration for the method and properties. However it is the responsibility of the class to provide definition while implementing it.

Now when do we use interfaces? Read about loose coupling and late binding. Here is a simple example to demonstrate a situation where we can use interfaces.

/// <summary>
/// This class should have a method that returns price of pet food. This class should be able to handle different pet animals
/// which as of now, is unknown
/// </summary>
class PetFood
{
    public decimal GetFoodPrice(string petType)
    {
        IPetAnimal petAnimal = null;

        if (petType == "Dog")
        {
            petAnimal = new Dog();
        }
        else if (petType == "Cat")
        {
            petAnimal = new Cat();
        }
        else
        {
            MessageBox.Show("This animal is not supported yet.");
            return 0M;
        }

        return petAnimal.GetFoodPrice();
    }
}

interface IPetAnimal
{
    decimal GetFoodPrice();
}

class Dog : IPetAnimal
{

    public decimal GetFoodPrice()
    {
        return 10M;
    }
}

class Cat : IPetAnimal
{
    public decimal GetFoodPrice()
    {
        return 5M;
    }
}
danish
  • 5,550
  • 2
  • 25
  • 28
0

You cannot create an instance of an interface. The Interface is some sort of contract that forces you to implement its members (which have no implementation code)

0

Your code will call the myfunc() method on your class instance. By implementing the interface you ensure that the method declared in the interface is defined in the class.

Les Hazlewood
  • 18,480
  • 13
  • 68
  • 76