Junior — Middle
Explain how abstract classes and interfaces differ in terms of inheritance implementation in object-oriented programming.
sobes.tech AI
Answer from AI
An abstract class is a class that contains at least one pure virtual function (without implementation), and it cannot be instantiated directly. It may contain both implemented and abstract methods, as well as fields.
An interface is a class that contains only pure virtual functions and has no state (fields). In languages like Java or C#, an interface is a contract that a class must implement.
In C++, an interface is usually implemented as an abstract class with only pure virtual methods and no fields.
Main differences:
- An abstract class can contain method implementations and fields, whereas an interface cannot.
- A class can inherit from only one abstract class (in languages with single inheritance), but can implement multiple interfaces.
Example in C++:
class Interface {
public:
virtual void foo() = 0; // pure virtual function
virtual ~Interface() {}
};
class AbstractClass {
public:
virtual void foo() = 0;
void bar() { /* implementation */ }
int data;
};