Java Notes
Complete guide to interfaces in Java — default methods, static methods, functional interfaces, multiple inheritance with interfaces, and modern interface design patterns.
An interface in Java is a contract that defines what a class can do without specifying how it does it. It's a collection of abstract method signatures that implementing classes must fulfill.
Interfaces enable multiple inheritance of type in Java — a class can implement many interfaces, gaining multiple capabilities while avoiding the Diamond Problem of multiple class inheritance.
Basic Interface Declaration
public interface Drawable {
void draw(); // Abstract by default (no body)
void resize(double factor);
String getDescription();
}
public interface Colorable {
void setColor(String color);
String getColor();
}
// A class can implement MULTIPLE interfaces
public class Circle implements Drawable, Colorable {
private double radius;
private String color = "black";
public Circle(double radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing " + color + " circle with radius " + radius);
}
@Override
public void resize(double factor) {
radius *= factor;
System.out.println("Resized to radius: " + radius);
}
@Override
public String getDescription() {
return "Circle (r=" + radius + ")";
}
@Override
public void setColor(String color) {
this.color = color;
}
@Override
public String getColor() {
return color;
}
}
public class Main {
public static void main(String[] args) {
Circle c = new Circle(5.0);
c.setColor("red");
c.draw();
c.resize(2.0);
c.draw();
System.out.println(c.getDescription());
}
}Drawing red circle with radius 5.0 Resized to radius: 10.0 Drawing red circle with radius 10.0 Circle (r=10.0)
Interface Members
| Member | Allowed? | Implicit Modifiers |
|---|---|---|
| Abstract methods | ✅ | public abstract |
| Default methods | ✅ (Java 8+) | public |
| Static methods | ✅ (Java 8+) | public |
| Private methods | ✅ (Java 9+) | private |
| Constants | ✅ | public static final |
| Instance fields | ❌ | — |
| Constructors | ❌ | — |
public interface MathOperations {
// Constants (implicitly public static final)
double PI = 3.14159265358979;
double E = 2.71828182845905;
// Abstract method (implicitly public abstract)
double calculate(double x, double y);
// Default method (Java 8+) — provides default implementation
default double square(double x) {
return x * x;
}
// Static method (Java 8+) — utility method on the interface
static double toRadians(double degrees) {
return degrees * PI / 180;
}
// Private method (Java 9+) — helper for default methods
private double validate(double x) {
if (Double.isNaN(x)) throw new IllegalArgumentException("NaN not allowed");
return x;
}
}Default Methods (Java 8+)
Default methods let you add new functionality to interfaces without breaking existing implementations:
Collection with 3 items Size: 3
Multiple Interface Inheritance
public interface Flyable {
void fly();
default String getMovement() { return "Flying"; }
}
public interface Swimmable {
void swim();
default String getMovement() { return "Swimming"; }
}
public interface Walkable {
void walk();
default String getMovement() { return "Walking"; }
}
// Implements ALL three — multiple inheritance!
public class Duck implements Flyable, Swimmable, Walkable {
@Override
public void fly() { System.out.println("Duck flying"); }
@Override
public void swim() { System.out.println("Duck swimming"); }
@Override
public void walk() { System.out.println("Duck walking"); }
// MUST override because multiple interfaces have the same default method
@Override
public String getMovement() {
return "Flying, Swimming, and Walking";
}
}
public class Main {
public static void main(String[] args) {
Duck duck = new Duck();
duck.fly();
duck.swim();
duck.walk();
System.out.println("Movement types: " + duck.getMovement());
// Interface references — polymorphism
Flyable flyer = duck;
flyer.fly();
Swimmable swimmer = duck;
swimmer.swim();
}
}Duck flying Duck swimming Duck walking Movement types: Flying, Swimming, and Walking Duck flying Duck swimming
Functional Interfaces (Java 8+)
An interface with exactly ONE abstract method. Can be used with lambda expressions:
@FunctionalInterface
public interface Transformer<T, R> {
R transform(T input);
}
@FunctionalInterface
public interface Validator<T> {
boolean validate(T input);
}
@FunctionalInterface
public interface Action {
void execute();
}
public class Main {
public static void main(String[] args) {
// Lambda expressions implement functional interfaces
Transformer<String, Integer> toLength = s -> s.length();
Transformer<Integer, Integer> doubled = n -> n * 2;
Validator<String> notEmpty = s -> s != null && !s.isEmpty();
Validator<Integer> positive = n -> n > 0;
System.out.println(toLength.transform("Hello")); // 5
System.out.println(doubled.transform(21)); // 42
System.out.println(notEmpty.validate("Java")); // true
System.out.println(notEmpty.validate("")); // false
System.out.println(positive.validate(-5)); // false
// Method reference
Transformer<String, String> toUpper = String::toUpperCase;
System.out.println(toUpper.transform("hello")); // HELLO
}
}5 42 true false false HELLO
Interface Inheritance
Interfaces can extend other interfaces:
public interface Readable {
String read();
}
public interface Writable {
void write(String content);
}
// Interface extending multiple interfaces
public interface ReadWritable extends Readable, Writable {
void seek(int position);
}
public class FileStream implements ReadWritable {
private StringBuilder content = new StringBuilder();
private int position = 0;
@Override
public String read() {
return content.substring(position);
}
@Override
public void write(String data) {
content.append(data);
}
@Override
public void seek(int position) {
this.position = position;
}
}Real-World Example: Plugin System
=== Starting Plugins ===
Starting: Logging Plugin v1.0.0
[Logger] Initialized
Starting: Security Plugin v2.1.0
[Security] Initialized — scanning for threats
=== Executing Plugins ===
[Logger] Processing: {user=alice, action=login}
[Security] Validating user: aliceCommon Mistakes
- Trying to add instance fields:
``java interface MyInterface { int count; // ❌ This is public static final! Must be initialized int count = 0; // This is a CONSTANT, not a mutable field } ``
- Not implementing all methods:
``java class MyClass implements Drawable, Colorable { @Override public void draw() { } // ❌ Missing resize(), getDescription(), setColor(), getColor() } ``
- Diamond problem with default methods:
``java interface A { default void hello() { System.out.println("A"); } } interface B { default void hello() { System.out.println("B"); } } class C implements A, B { // ❌ Compile error! Must override hello() to resolve conflict @Override public void hello() { A.super.hello(); } // ✅ Choose A's version } ``
- Forgetting
@FunctionalInterfacefor lambda use:
``java // Without annotation, compiler won't warn if you add second method @FunctionalInterface // ✅ Compile error if more than 1 abstract method interface Processor { void process(); } ``
Best Practices
- Keep interfaces small and focused (Interface Segregation Principle)
- Use
@FunctionalInterfacefor interfaces meant for lambdas - Use default methods for backward-compatible evolution
- Prefer interfaces over abstract classes for defining capabilities
- Name interfaces by capability:
Runnable,Comparable,Serializable - Don't prefix with
I— Java convention uses clean names:List, notIList
Interview Questions
Q1: Can an interface have a constructor? No. Interfaces cannot be instantiated and have no state to initialize.
Q2: Can an interface extend a class? No. Interfaces can only extend other interfaces. Classes implement interfaces.
Q3: What is a marker interface? An interface with no methods (e.g., Serializable, Cloneable). It "marks" a class as having a capability, checked via instanceof.
Q4: What happens if a class implements two interfaces with the same default method? Compile error. The class must override the method to resolve the conflict, optionally calling one with InterfaceName.super.method().
Q5: Can we have private methods in an interface? Yes, since Java 9. Used as helpers for default methods.
Q6: Why can a class implement multiple interfaces but not extend multiple classes? Interfaces only define contracts (no state conflicts). Multiple class inheritance risks state ambiguity (Diamond Problem) with instance fields.
Q7: What is the difference between abstract class and interface? When to use each? Abstract class: shared state, partial implementation, single inheritance. Use for IS-A with common fields. Interface: pure contract, multiple inheritance, no state. Use for CAN-DO capabilities.
Q8: What are default methods in interfaces (Java 8+)? Default methods have a body: default void method() { ... }. They allow adding new methods to interfaces without breaking existing implementations. Classes implementing the interface inherit the default behavior but can override it. This solved the interface evolution problem.
Q9: What is a functional interface? A functional interface has exactly ONE abstract method (can have multiple default/static methods). It can be used with lambda expressions. Examples: Runnable, Comparator, Predicate. Annotate with @FunctionalInterface for compiler verification.
Q10: What is a marker interface? Give examples. A marker interface has no methods — it's an empty interface used to signal/mark a capability. Examples: Serializable (object can be serialized), Cloneable (object can be cloned), RandomAccess (list supports fast random access). Modern Java prefers annotations over marker interfaces.
Q11: Can interfaces have constructors? No. Interfaces cannot have constructors because they cannot be instantiated and don't have instance state to initialize. Interface variables are implicitly public static final (constants) and must be initialized at declaration.
Q12: How does Java resolve conflicts when a class implements two interfaces with the same default method? The class MUST override the conflicting method and provide its own implementation. Inside the override, you can choose one: InterfaceA.super.method() or InterfaceB.super.method(). Without the override, it's a compile error.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Interface in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, oops, interface, interface in java
Related Java Master Course Topics