Java Abstract Classes and Interfaces
Abstraction is one of the four pillars of object-oriented programming. It aims to hide complex implementation details and expose only the necessary functionality to users. In Java, abstraction is primarily achieved through two mechanisms: Abstract Classes and Interfaces.
Abstract Class
An abstract class is a class that cannot be instantiated and serves as a parent class (base class) for other classes. It's used to define a general template for a type, which can include some already implemented concrete methods and some abstract methods that must be implemented by subclasses.
- Use the
abstractkeyword to declare an abstract class. - An abstract class can contain instance variables, constructors, concrete methods (with a body), and abstract methods.
- Abstract method: Has only a method signature with no body, declared using the
abstractkeyword. Any subclass that inherits an abstract class must implement all of its abstract methods, unless that subclass itself is also an abstract class.
Interface
An interface is a completely abstract reference type that defines a set of methods (behavioral contract). Any class that implements the interface must provide concrete implementations for these methods. Interfaces are a way to achieve multiple inheritance.
- Use the
interfacekeyword to declare an interface. - All methods in an interface are
public abstractby default (before Java 8). - All variables in an interface are
public static finalby default (i.e., constants). - A class uses the
implementskeyword to implement one or more interfaces.
Java 8+ Interface Enhancements
Starting from Java 8, interfaces can contain default methods and static methods, adding more flexibility to interfaces.
- Default method (
defaultmethod): Allows providing a default implementation for a method in an interface. Classes implementing the interface can use the default version without overriding it. - Static method (
staticmethod): Belongs to the interface itself and can only be called through the interface name.
Abstract Class vs. Interface
When to Use?
- Use abstract class: When you want to create a base class that contains common code and state shared by subclasses. When there's a clear hierarchy and "is-a" relationship between classes (e.g.,
Dogis anAnimal). - Use interface: When you want to define a role or capability that can be possessed by classes at different hierarchies. When you want a class to have multiple unrelated behaviors (e.g., a
Birdclass can implement bothFlyableandSingableinterfaces).