About Lesson
Feature | Interface | Abstract Class |
---|---|---|
Definition | A reference type that can contain only abstract methods (until Java 7), default methods, static methods (Java 8+), and constants. Interface can’t provide the implementation of abstract class. | A class that cannot be instantiated and can contain abstract methods as well as concrete methods. Abstract class can provide the implementation of interface. |
Purpose | To define a contract that implementing classes must follow. | To provide a common base for subclasses to extend, including common methods and fields. |
Syntax | public interface MyInterface { … } | public abstract class MyAbstractClass { … } |
Instantiation | Cannot be instantiated directly. | Cannot be instantiated directly. |
Multiple Inheritance | A class can implement multiple interfaces. | A class can extend only one abstract class. |
Method Implementation | Cannot have method implementations (until Java 7). Java 8+ allows default and static methods. | Can have both abstract methods (without implementation) and concrete methods (with implementation). |
Default Methods | Supported (from Java 8 onwards). | Not applicable. |
Static Methods | Supported (from Java 8 onwards). | Supported. |
Fields | Can only contain static final constants. | Can contain instance variables and static variables. |
Access Modifiers for Methods | All methods are implicitly public and abstract (until Java 7). Java 8+ allows public and default for default methods, public and private for static methods. | Methods can be public, protected, private, or package-private. |
Access Modifiers for Fields | Fields are implicitly public, static, and final. | Fields can have any access modifier (public, protected, private, or package-private). |
Constructors | Interfaces do not have constructors. | Can have constructors, which are called when a subclass is instantiated. |
Use Case | Used to define a contract for multiple unrelated classes to implement. | Used to define common behavior and state that can be inherited by related classes. |
Inheritance Keyword | implements keyword is used by classes to implement an interface. | extends keyword is used by classes to extend an abstract class. |
When to use which
Interface
- Use interfaces when you need to provide a contract for multiple unrelated classes to implement.
- Use interfaces to achieve multiple inheritance-like behavior in Java.
- Use interfaces for maximum flexibility and loose coupling.
Abstract Class
- Use abstract classes when you want to define a common base for related classes to inherit from.
- Use abstract classes when you need to provide default behavior along with abstract methods.
- Use abstract classes when you want to provide a template for subclasses to follow.