Abstract Class vs Interface in Java
In Java, both abstract classes and interfaces are used to define common behavior and characteristics for a group of related classes. However, they differ in several key aspects:
Inheritance
- Abstract Class: A class can extend only one abstract class.
- Interface: A class can implement multiple interfaces.
Method Definitions
- Abstract Class: Can have both abstract and non-abstract (concrete) methods.
- Interface: All methods in an interface are implicitly abstract and public by default, unless they are default or static methods introduced in Java 8.
Instance Variables
- Abstract Class: Can have instance variables, which can be of any access modifier (public, private, protected, or default).
- Interface: Can have only static and final (constant) variables.
Access Modifiers
- Abstract Class: Can have methods and variables with any access modifier (public, private, protected, or default).
- Interface: All methods (except default and static methods) and variables are implicitly public.
Implementation
- Abstract Class: Can provide method implementations and have constructor.
- Interface: Cannot have constructors, and all methods (except default and static methods) must be implemented by the implementing classes.
Use Cases
- Abstract Class: Useful when you want to provide some common functionality and state, and also allow subclasses to override or extend the provided implementation.
- Interface: Useful when you want to define a contract or a set of methods that a class must implement, without providing any implementation details.
Here's a simple example to illustrate the differences:
// Abstract Class
abstract class Animal {
protected String name;
public abstract void makeSound();
public void eat() {
System.out.println("The animal is eating.");
}
}
// Interface
interface Flyable {
void fly();
int MAX_ALTITUDE = 10000; // Implicitly public, static, and final
}
// Concrete Class
class Bird extends Animal implements Flyable {
public Bird(String name) {
this.name = name;
}
@Override
public void makeSound() {
System.out.println("The bird is chirping.");
}
@Override
public void fly() {
System.out.println("The bird is flying.");
}
}
public class Main {
public static void main(String[] args) {
Bird bird = new Bird("Tweety");
bird.makeSound(); // The bird is chirping.
bird.eat(); // The animal is eating.
bird.fly(); // The bird is flying.
System.out.println("Max altitude: " + Flyable.MAX_ALTITUDE); // Max altitude: 10000
}
}
Here's a Mermaid diagram to visualize the key differences:
In summary, abstract classes and interfaces in Java serve different purposes. Abstract classes are useful when you want to provide some common functionality and state, while interfaces are more suitable for defining contracts and common behavior without implementation details. The choice between the two depends on the specific requirements of your design and the level of abstraction you need to achieve.