- Abstract Class:
- Purpose: Used when you want to provide a base class with common functionality for other classes to inherit.
- Methods: Can have both abstract methods (no body, must be implemented in child classes) and concrete methods (with implementation).
- Inheritance: A class can extend only one abstract class because Java doesn’t support multiple inheritance.
- Variables: Can have instance variables (non-static) and constants.
- Constructors: Can have constructors to initialize variables or perform setup when the abstract class is inherited.
- Example:
abstract class Animal { String name; Animal(String name) { // Constructor this.name = name; } abstract void makeSound(); // Abstract method void eat() { // Concrete method System.out.println(name + " is eating."); } } class Dog extends Animal { Dog(String name) { super(name); } @Override void makeSound() { System.out.println("Bark!"); } }
- Interface:
- Purpose: Defines a contract or behavior that multiple, unrelated classes can implement.
- Methods:
- Before Java 8: Only abstract methods (no implementation).
- After Java 8: Can have default methods (with implementation) and static methods.
- Inheritance: A class can implement multiple interfaces, which allows a form of multiple inheritance.
- Variables: Can only have public, static, and final constants (no regular variables).
- No Constructors: Interfaces cannot have constructors because they are not meant to create objects.
- Example:
interface AnimalActions { void makeSound(); // Abstract method default void sleep() { // Default method System.out.println("Sleeping..."); } } class Cat implements AnimalActions { @Override public void makeSound() { System.out.println("Meow!"); } }
Key Differences in Simple Terms:
- Abstract Class:
- Use it when you want to share code among related classes.
- Can extend only one abstract class.
- Can have variables, constructors, and regular methods.
- Interface:
- Use it to define behaviors that any class can implement.
- A class can implement multiple interfaces.
- Only has constants and abstract/default/static methods.