Junior
What is an interface and how does it differ from an abstract class?
sobes.tech AI
Answer from AI
Interface is a contract that defines a set of methods that a class must implement. It does not contain implementations of these methods and cannot have state fields (except constants). It is used to define object behavior and multiple inheritance of behavior.
An abstract class can contain both abstract (without implementation) and concrete (with implementation) methods. It can have state fields and is used to define common structure and behavior for subclasses. Multiple inheritance from abstract classes in Java is not possible.
Key differences:
- Method implementation: Interface has no implementation, abstract class can have.
- State fields: Interface has no state fields (except constants), abstract class can have.
- Multiple inheritance: A class can implement multiple interfaces but inherit only one abstract class.
- Constructors: Interface cannot have constructors, abstract class can.
Example of an interface:
interface Drawable {
void draw(); // Abstract method
}
Example of an abstract class:
abstract class Shape {
protected int x, y; // State fields
public Shape(int x, int y) {
this.x = x;
this.y = y;
}
abstract void display(); // Abstract method
void moveTo(int newX, int newY) { // Concrete method
x = newX;
y = newY;
}
}