Interfaces and Abstract Classes
🔷 Interfaces in Java
An interface in Java is a reference type similar to a class, but it is used to specify a contract that a class must follow. It contains abstract methods (without implementation) and constants. From Java 8 onwards, interfaces can also have default and static methods.
✅ Key Points
-
Declared using the
interfacekeyword. -
All methods in an interface are
publicandabstractby default (until Java 7). -
All fields are
public,static, andfinal(i.e., constants). -
A class implements an interface using the
implementskeyword. -
A class can implement multiple interfaces (Java supports multiple interface inheritance).
-
Interfaces cannot have constructors.
🧩 Syntax
✅ Implementing an Interface
✳️ Java 8+ Enhancements
Interfaces can now have:
-
defaultmethods: with a body -
staticmethods: utility methods
🔷 Abstract Classes in Java
An abstract class in Java is a class that cannot be instantiated, and it is used to define common behavior for a group of related subclasses. It may contain both:
-
Abstract methods (without a body),
-
Concrete methods (with a body),
-
Fields (variables), and
-
Constructors.
✅ Definition
🔑 Key Points
-
Use the
abstractkeyword to declare an abstract class or method. -
An abstract class cannot be instantiated directly.
-
If a class contains at least one abstract method, it must be declared abstract.
-
Subclasses must override all abstract methods unless they are also declared abstract.
✅ Example
📌 When to Use Abstract Classes?
-
When you want to share code among several related classes.
-
When you want to define a template for future subclasses.
-
When you want to partially implement a class and leave the rest for subclasses.
🆚 Abstract Class vs Interface (Quick Comparison)
| Feature | Abstract Class | Interface |
|---|---|---|
| Can have fields | ✅ Yes | ❌ No (only constants) |
| Constructors | ✅ Yes | ❌ No |
| Concrete methods | ✅ Yes | ✅ Yes (from Java 8) |
| Inheritance | Single inheritance | Multiple implementation |
| Instantiation | ❌ Not allowed | ❌ Not allowed |
📊 3. Interface vs Abstract Class: Comparison Table
| Feature | Interface | Abstract Class |
|---|---|---|
| Keyword | interface | abstract |
| Method types | Only abstract (till Java 7); from Java 8, default and static | Abstract and concrete methods |
| Access modifier for methods | All methods are public by default | Can be private, protected, etc. |
| Fields | Only public static final (constants) | Can have instance variables |
| Constructors | No | Yes |
| Multiple inheritance | Yes (a class can implement many) | No (single inheritance) |
| Inheritance keyword | implements | extends |
| Instantiable | No | No |
| Use case | When you need a contract (what to do) | When you need partial implementation (how to do) |
Comments
Post a Comment