Core Module
12 min forge
Java Interfaces
Defining contracts, multiple inheritance of type, and default methods.
Java Interfaces
π What is it
An Interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. It provides a way to achieve 100% abstraction (before Java 8) and multiple inheritance of type.
β‘ When to use
Use interfaces to define a "contract" that classes must follow (e.g., Runnable, Comparable). Use them when you want to define what a class should do, but not how it should do it.
ποΈ Key Concepts
implementsKeyword: Used by a class to inherit from an interface.- Default Methods (Java 8+): Methods with a body that provide a default implementation.
- Multiple Inheritance: A class can implement multiple interfaces.
- Loose Coupling: Interfaces help in reducing dependencies between classes.
π» Code example
java Standardinterface Printable { void print(); // Abstract method default void scan() { System.out.println("Scanning..."); } } class LaserPrinter implements Printable { public void print() { System.out.println("Printing using Laser..."); } } public class Main { public static void main(String[] args) { LaserPrinter lp = new LaserPrinter(); lp.print(); lp.scan(); // Uses default implementation } }
β Common mistakes
- Instantiating Interfaces: Trying to do
new MyInterface()(interfaces cannot be instantiated). - Public access: Forgetting that all methods in an interface are
publicandabstractby default. - Overusing Default Methods: Using default methods for core logic (they should be used for backward compatibility).