Interfaces in C++ are implemented using abstract classes with pure virtual functions, while languages like Java provide a dedicated interface
 keyword.
Here are some key differences between C++ and Java interfaces:
Syntax: In C++, interfaces are created using abstract classes with pure virtual functions.
class IShape {
public:
virtual void Draw() = 0;
};
Multiple Inheritance: C++ allows a class to implement multiple interfaces using multiple inheritance.
class Circle
: public IShape, public IOtherInterface {
public:
void Draw() override {
// Implementation
}
};
Implementation: C++ interfaces can include non-pure virtual functions with implementations, providing default behavior.
class IShape {
public:
virtual void Draw() = 0;
virtual void Print() {
std::cout << "Shape\n";
}
};
No Interface Keyword: C++ does not have a specific keyword for interfaces; abstract classes serve this purpose.
Syntax: Java provides a specific interface
keyword to define interfaces.
public interface Shape {
void draw();
}
Single Inheritance with Implements: Java uses the implements
keyword to indicate that a class implements an interface. Java supports single inheritance for classes but allows multiple interface implementations.
public class Circle
implements Shape, OtherInterface {
public void draw() {
// Implementation
}
}
Default Methods: Java interfaces can include default methods with implementations, providing common functionality that can be overridden.
public interface Shape {
void draw();
default void print() {
System.out.println("Shape");
}
}
Specific Keyword: Java explicitly distinguishes interfaces from classes with the interface
keyword, making it clear that the type is intended to be used as a contract.
interface
keyword, whereas C++ uses abstract classes with pure virtual functions.Using an abstract IShape
class in C++ looks like this:
#include <iostream>
class IShape {
public:
virtual void Draw() = 0;
virtual void Print() {
std::cout << "Shape\n";
}
};
class Circle : public IShape {
public:
void Draw() override {
std::cout << "Drawing Circle\n";
}
};
Using a Shape
interface in Java looks like this:
public interface Shape {
void draw();
default void print() {
System.out.println("Shape");
}
}
public class Circle implements Shape {
public void draw() {
System.out.println("Drawing Circle");
}
}
Both examples achieve similar outcomes but use different syntax and concepts based on the language's design principles.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to create interfaces and abstract classes using pure virtual functions