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

谁都会走 提交于 2020-01-13 18:01:30

问题


Possible Duplicate:
Interface vs Abstract Class (general OO)

Can I ever instantiate 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?


回答1:


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.




回答2:


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.




回答3:


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



回答4:


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.




回答5:


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




回答6:


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.



来源:https://stackoverflow.com/questions/3702498/what-is-the-difference-between-an-abstract-class-and-an-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!