Difference between abstract class and interface [

2020-06-23 06:57发布

问题:

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

Possible Duplicate:
Interface vs Base class

I am not understanding the difference between an abstract class and an interface. When do I need to use which art of type?

回答1:

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.

article along with the demo project discussed Interfaces versus Abstract classes.



回答2:

Try thinking of it like this:

An abstract class creates an "is-a" relationship. Volkswagon is a Car.

An interface creates a "can-do" relationship. Fred can IDrive.

Moreover, Fred can IDrive, but Fred is a Person.



回答3:

An abstract class is class probably with some abstract methods and some non-abstract methods. They do stuff (have associated code). If a new non-abstract class, subclasses the abstract class it must implement the abstract methods.

I.E.

public abstract class A {
    public string sayHi() { return "hi"; } // a method with code in it
    public abstract string sayHello();  // no implementation
}

public class B 
   : A
{
    // must implement, since it is not abstract
    public override string sayHello() { return "Hello from B"; }
}

Interface is more like a protocol. A list of methods that a class implementing that interface must have. But they don't do anything. They have just method prototypes.

public interface A
{
    string sayHi(); // no implementation (code) allowed
    string sayHello();  // no implementation (code) allowed
}

public class B
    : A
{
     // must implement both methods
    string sayHi() { return "hi"; }
    string sayHello() { return "hello"; }
}

Both are often confused because there is no protocol/interface in C++. So the way to simulate an interface behavior in that language is writing a pure virtual class (a class with only pure virtual functions).

class A {
    virtual int a() = 0;  // pure virtual function (no implementation)
}