开发者

What is the difference between an abstract class and an interface? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Interface vs Abstract Class (general OO)

Can I ever instanti开发者_C百科ate an Abstract class? If so, why would I not make all my non-sealed classes abstract?

If I can't instantiate it, then what is the difference from an interface? Can the abstract class have "base" class functionality? Is there more to the difference between an interface and an abstract class than that?


You can't instantiate an abstract class.

The difference between an abstract class and an interface is that an abstract class can have a default implementation of methods, so if you don't override them in a derived class, the abstract base class implementation is used. Interfaces cannot have any implementation.


Interfaces don't provide an implementation. You can also implement multiple interfaces.

You can provide an implementation inside of an abstract class, but you can only inherit from one base type.

In either case, you can't directly instantiate either one.


You cannot directly create an instance of an abstract class. You can, however, provide method and/or property implementations, which you cannot do in an interface. Also you can only inherit one class, abstract or otherwise, whereas you can inherit (implement) as many interfaces as you like.

abstract class A 
{
    public int Foo() { return 1; } // implementation defined
}

class B : A 
{
}

interface C
{
    int Foo() {return 1;} // not legal, cannot provide implementation in interface
}

// ... somewhere else in code

A a = new A(); // not legal
A a = new B(); // legal


Abstract Class:

  1. Abstract Class Can contain Abstract Methods and Non- Abstract Methods.

  2. When a Non-Abstract Class is Inherited from an Abstract Class, the Non-Abstract Class should provide all the implementations for the inherited Abstract Method.

Interface:

  1. Interface is nothing but Pure Abstract Class ie Interface can contain only the function declaration.

  2. All the members of the interface are Public by Default and you cannot provide any access modifiers.

  3. When a class is inherited from the interface, the inherited class should provide actual implementations for the inherited members.


For one thing: You can only inherit from one abstract class. You can have multiple interfaces attached to a class.


Interface defines a contract, your saying that you will guantee implimitations of a specific set of method signatures.

An abstract class just means you can't directly create a new instance of it, your free to use any other class features, ie properties.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜