Click here to Skip to main content
14,875,113 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello People
I have few questions on Interfaces:

1) - What is the difference between an interface and an abstract class? Because in both we dont implement the methods. I have heard people saying that it is a sort of a contract, because the class which inherits an interface will have to implement its methods. But the same goes with an abstract class.
- The only difference what i see is that interface provides a mechanism of multiple inheritance because multiple inheritance of classes are not allowed.

2) - why does an interface not contain access modifiers? also why does it not contain static or instance methods. However i think that the reason behind not declaring static methods is CLI.
- Common Language Infrastructure compliant languages dont have an interface with static methods so that other languages should have no problem accessing them.

3) is this possible:
C#
Interface i = new Class1(); /// let us say if : Class1 : Interface
// and 
Interface i = (Interface) new Class1(); //// I have done casting if there is no inheritance that means no relationship between Class1 and Inheritance.


Thanks
Posted
Updated 20-Aug-13 12:07pm
v2
Comments
Rahul VB 21-Aug-13 9:04am
   
Guys i hope that i have quotted my question correctly. Thanks to guide me with your solutions. I have one more question for you :

i have
Class c
{

}

Interface i
{


}

Class d : c,i //// This is allowed but,

Class d: i,c //// this is not allowed

What is the reason behind this ?

Thanks again to help me...

1.
You CAN implement methods in abstract classes. The difference is this:

Interface: Basically a promise (contract) to implement a particular set of methods/properties. No matter what other implementation the implementor creates (additional methods, properties), this defines a base interface to that class (hence the name).

Abstract: This is a base class implementation. Take for example an Engine class, it has a defined set of functions like Start, Stop, Increase RPM, Decrease RPM, etc. Those methods can be implemented (concrete). You can also define methods that must be implemented (virtual) in the derived classes because it doesn't make sense to implement them at the base level. You can also define methods that can either be left as the base implementation or overridden in the derived class (abstract).

2. Interfaces don't have access modifiers because they are, by definition, public (edit: public to the implementor classes and consumers of the class, as Sergey said, the interface itself can be marked with any valid access modifier, interface methods must be marked public, but the class that implements it can also be any modifier that is MORE or AS restrictive as the interface, aka you can't implement an internal interface on a public class, try it) . It doesn't make sense to have an access modifier like protected or private because you are then dictating the internal structure of the derived class. Interfaces are just that, an external interface to a class, so how do you make an external class dictate internal structure? Thats a better use for abstract classes.

3. The first one is possible, the second is not unless Class1 or something up the inheritance stream implements the interface.
   
v2
Comments
Sergey Alexandrovich Kryukov 20-Aug-13 17:58pm
   
It's all correct, but perhaps needs some more detail to really explain things.
I tried to cover it, but it's hard to say what may else many be needed to make it comprehensive. Please see my answer, may be you can add something which is missing.

In particular, even though the code shown in #3 is formally correct and will, as you say, work, this is a misuse of interface references, should be pointed out.
The statement "interfaces are, by definition, public" is inaccurate. I explained it in my answer; besides, the interface itself can have any access modifier, it makes full sense. But not a member of an interface...


(Oh, I missed one important but advanced topic: physical address of an object cast to different interface types implemented by the same runtime type is different; this is pretty hard to explain in an understandable way, and not so easy to see in .NET...)

—SA
Ron Beyer 20-Aug-13 18:01pm
   
Reading through it now, will take me a minute :)
Sergey Alexandrovich Kryukov 20-Aug-13 18:06pm
   
Please refresh the page, as I added to the comment above and fixed some typo in the answer...
—SA
Ron Beyer 20-Aug-13 18:18pm
   
I worded that interfaces thing wrong, I will edit it, thanks for pointing it out!
Sergey Alexandrovich Kryukov 20-Aug-13 18:21pm
   
:-)
Maciej Los 20-Aug-13 18:10pm
   
Deserves for 5!
Ron Beyer 20-Aug-13 18:16pm
   
Thanks!
thatraja 11-Dec-13 4:34am
   
5!
Let's see:

  1. Generally speaking, the questions like "what's the difference between X and Y" are incorrect. (What is the difference between apple and Apple? :-)) Sometimes, it is impossible to give the definition of difference, the concept itself may be undefined, sometimes it just needs the definition, which can be difficult. Usually, "difference" only applies to some very close things. You added some detail and removed another detail, than it could be difference. Not always the case, so better avoid such questions.

    So, is interface similar to an abstract class or not? In fact, yes and no.

    Indeed, historically, interface originated from the concept of abstract class. If you look at COM interfaces, you will see, that their functionality is based on the memory layout fully identical to that of some class of "pure abstract classes", that is, the classes without fields, only with functions, and all functions are pure virtual. The binary structure of the classes referenced by interface pointers still follow the same schema.

    However, semantically interfaces are considerably different. One thing is the multiple inheritance you mentioned. This is called weak form of multiple inheritance. It introduce considerable limitation (read "weakness" compared to "full" multiple inheritance and at the same time removes multiple-inheritance controversies. Buy the way, it also applies to the "pure abstract classes" mentioned above.

    Another big difference in .NET is this: struct types cannot be derived, but they can implement interfaces, exactly as classes. It means another, more advanced type of polymorphism: first, polymorphic object sets can be abstracted not only out of concrete types, but even from the knowledge about the nature of the type: reference type of value type. Besides, due to multiple inheritance, the same object can be a member in different polymorphic sets at the same time, even if those sets are based on different "base types" (if I can use the analogy with "base classes"), that is, different compile-time types defining membership in a polymorphic set.

    Note that I mean polymorphism in the wide sense of this word. For example, a method parameter of interface type (or non-sealed class type, for this matter) defines some polymorphic set of valid runtime types of an actual parameter. Please see:
    http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29[^].

    But the real "difference" is the different roles in code design. Please see these past answers:
    How to realize interface?[^],
    When we use abstract and when we use interface...?[^],
    Difference between abstract class and interface if they have same no of methods and var[^],
    How to decide to choose Abstract class or an Interface[^],
    Interfaces and Polymorphism[^].
  2. Access modifiers are not needed for interfaces. The real access is defined by the implementing class and is different for explicit and implicit implementation of interface:
    C#
    interface IFirst {
       void SomeMethod();
    }
    
    interface ISecond {
       void AnotherMethod();
    }
    
    class Implementation : IFirst, ISecond {
        void IFirst.SomeMethod() {/* ... */} // explicit, only accessible via IFirst reference
        public void AnotherMethod() {/* ... */} // implicit, accessible publicly
    }


    If you could specify the access for these two methods in interfaces themselves, it would not make any sense. For example, if access could be private, how a class could be "interfaced"? :-)
  3. You can do things of these sort (but only if the class really implements the interface, otherwise invalid cast exception will be thrown), but it would defeat the purpose of interfaces, to certain extent. You should better avoid such things. The intended usage patters are different. Using the definitions given above:
    C#
    IFirst first = new Implementation();
    
    // from this point, use the object only through interface:
    first.SomeMethod();
    // or, you use the formal parameters of IFirst type, when the runtime type it not accessible:
    
    //...
    void SomeMethodAcceptingAbstactParameter(IFirst first) {
        // there is no a way to access members of implementing class/structure, even internal or public ones: good encapsulation
    }
    
    //dual use, sometime handy:
    Implementation implementation = new Implementation();
    implementation.AnotherMethod();
    
    ISecond second = new Implementation();
    second.AnotherMethod(); // but no access to other Implementation members
  4. Overall, explicit implementation stimulates the use of the object only through the interface and thus has considerable advantages, but sometimes implicit is also needed. And you have no choice if some base class already implemented interface member using some virtual method; you can only override it.


[EDIT]

Please see my recent answer where I explained polymorphism based in interfaces in detail: POLYMORPHISM WITHOUT OVERLOADING AND OVERRRIDING IS POSSIBLE[^].

—SA
   
v9
Comments
Maciej Los 20-Aug-13 18:09pm
   
The Wizard of Words!
+5!
Sergey Alexandrovich Kryukov 20-Aug-13 18:10pm
   
Than you for your nice Oz! :-)
—SA
Maciej Los 20-Aug-13 18:21pm
   
;)
Ron Beyer 20-Aug-13 18:13pm
   
+5, extremely well said as usual...

.NET is a very flexible language, more flexible than most people realize even without true polymorphism. A full understanding of interfaces and abstract classes is key to good OOD. Advanced topics like implicit/explicit implementations, casting, and even boxing/unboxing as different types are difficult to grasp. A good study of the .NET type system is always recommended for the novice and elite alike.

To demonstrate the power of .NET you can do some things like marshal/unmarshal between managed/unmanaged and back to managed to do some really weird things. Not necessarily that you should.

Also, a good understanding of these concepts really lets you apply design patterns correctly, and studying design patterns can help understand what interfaces and abstract classes can be used for. I would recommend picking up a good book on design patterns to really get a grasp on these concepts.
Sergey Alexandrovich Kryukov 20-Aug-13 18:20pm
   
Golder words...
Thank you very much, Ron.
—SA
thatraja 11-Dec-13 4:34am
   
5!
Sergey Alexandrovich Kryukov 11-Dec-13 10:30am
   
Thank you, Raja.
—SA
[no name] 23-May-14 7:31am
   
nice presentation
CPallini 22-Jun-14 4:57am
   
My 5.
To add to what was already said...

"The only difference what i see is that interface provides a mechanism of multiple inheritance"

Interfaces have nothing to do with inheritance -- classes that are totally unrelated can implement the same Interface.
   
Comments
Maciej Los 20-Aug-13 18:41pm
   
It looks like a comment rather than answer ;(
I would suggest you to delete it to avoid down-voting
I'm staying indifferent to voting system.
PIEBALDconsult 20-Aug-13 18:43pm
   
I really can't be bothered.
Maciej Los 20-Aug-13 18:57pm
   
Why? Who wants to get negatives?
PIEBALDconsult 20-Aug-13 19:52pm
   
I think you're taking this too seriously.
Maciej Los 21-Aug-13 1:41am
   
Have a 5 for positive mindset ;)
Maciej Los 21-Aug-13 1:42am
   
A5 for positive mindset!
BillWoodruff 11-Dec-13 3:38am
   
+5 A very good point !
thatraja 11-Dec-13 4:33am
   
Counter
1. In an abstract class, you can have some of the methods with their default implementation but in interface all methods should not have any implementation. The main difference between both is that interfaces are best for generic programming. You just define the interfaces with methods which must be there let the developer decide which method of an interface should have which functionality according to his need. The abstract class can't have such functionality just because they may have the implementation of at least one method. So, in that case an abstract class may not be able to serve for purely generic level programming.

2. Interfaces are built with the thing in mind that all methods in an interface should be implemented by the class which is inheriting those interfaces; that is why all methods in the interface are by-default set as public so that they can be accessible with the implementer class. Let's say if a method's access modifier is private, then it won't be accessible by its inheriting class and also there is no reason for such a method to be in the interface as it has no implementation as well. So there is no logic to have in an interface which is never going to be implemented by the inheriting class and which have no implementation as well. But if there is such an interface which have lots of methods and you think that not every class needs all those methods then it is a good idea to break that interface WISELY to create multiple interfaces so that each interface may have only those methods which SHOULD really be there.

3. the following statement is possible.
VB
Interface i = new Class1(); 


The following statement is possible only if the Class1 implements the interface.

Interface i = (Interface) new Class1()
   
Comments
Sergey Alexandrovich Kryukov 20-Aug-13 18:19pm
   
Even though there are many correct statements here, the answer is highly misleading, mainly due to misleading term "generic programming". It sounds like associated with .NET generics, but it should not (even if you didn't mean it). Actually, you did not say anything essential on interfaces vs. abstract classes.

"By default set as public" is also incorrect. First, members of interfaces are not just methods. More importantly, interface members have special access (either public or only through interface reference), which you might be unaware of.

Besides, this answer is simply redundant. I suggest you should be more careful with answers, as naive inquirers can easily be mislead.

—SA
See: [^]

Hope, this will helps you...
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900