abstract class vs interface
Abstract Class:
- Definition: A class declared with the abstract keyword, which may or may not have abstract methods.
- Method Implementation: Can have abstract methods (methods without a body) and concrete methods (with implementation).
- Fields: Can have instance variables and constructors.
- Constructor: Can have constructors.
- Access Modifiers: Can have different access modifiers for methods and fields.
- Multiple Inheritance: Does not support multiple inheritance (extends only one class).
- Purpose: Used to provide a common base for subclasses.
Table of Contents
Example
abstract class Shape {
abstract void draw();
void display() {
System.out.println("Displaying shape");
}
}
Interface:
- Definition: A reference type in Java similar to a class, but contains only abstract methods, constants, and default methods.
- Method Implementation: Contains only abstract methods (methods without a body) by default. From Java 8 onwards, it can also have default and static methods with implementation.
- Fields: Can only have constants (public, static, final fields).
- Constructor: Cannot have constructors.
- Access Modifiers: All methods are implicitly public, and all fields are implicitly public, static, and final.
- Multiple Inheritance: Supports multiple inheritance (extends multiple interfaces).
- Purpose: Used to achieve abstraction and support multiple inheritance of type.
Example
interface Drawable {
void draw();
default void display() {
System.out.println("Displaying drawable");
}
}
Key Differences
- 1. Method Implementation:
- Abstract Class: Can have both abstract and concrete methods.
- Interface: Contains only abstract methods (before Java 8). From Java 8 onwards, it can have default and static methods with implementation.
- 2. Fields:
- Abstract Class: Can have instance variables and constants.
- Interface: Can only have constants (public, static, final fields).
- 3. Constructor:
- Abstract Class: Can have constructors.
- Interface: Cannot have constructors.
- 4. Access Modifiers:
- Abstract Class: Can have different access modifiers for methods and fields.
- Interface: All methods are implicitly public, and all fields are implicitly public, static, and final.
- 5. Multiple Inheritance:
- Abstract Class: Does not support multiple inheritance (extends only one class).
- Interface: Supports multiple inheritance (extends multiple interfaces).
- 6. Purpose:
- Abstract Class: Used to provide a common base for subclasses.
- Interface: Used to achieve abstraction and support multiple inheritance of type.
Understanding these differences helps in designing and implementing object-oriented systems effectively in Java.