Java Notes
Learn Java interfaces — what an interface is, how to implement one, multiple implementation, default and static methods, functional interfaces, and when to choose interface over abstract class.
An interface is a contract. It lists what methods a class must provide, without writing how those methods work. Any class that agrees to the contract uses implements and writes the actual code.
The caller only knows the contract — not the specific class. This creates maximum flexibility.
Basic Interface Syntax
public interface Drawable {
void draw(); // abstract by default — no body needed
void resize(int factor);
}- Every method in an interface is
publicandabstractby default, even without those keywords. - No constructor. No instance fields. Only method declarations (and constants).
Implementing an Interface
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Line by line:
class Circle implements Drawable— Circle promises to providedraw()andresize().Drawable d1 = new Circle(5.0);— interface reference holding a Circle object. Onlydraw()andresize()are visible throughd1.- If you do not implement all interface methods, Java gives a compile error.
Multiple Interfaces — One Class, Many Contracts
A class can implement multiple interfaces. This is Java's solution to multiple inheritance.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Report is both Printable and Exportable. The same object can be stored in either interface reference. This is not possible with class inheritance — a class can only extend one parent.
Default Methods (Java 8+)
Before Java 8, interfaces could only have abstract methods. Java 8 added default methods — methods with a body inside an interface. This allows adding new methods to interfaces without breaking existing implementations.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Neither FormalGreeting nor CasualGreeting had to write greetAll(). They inherited the default version which calls their own greet().
Static Methods in Interface
Interfaces can also have static methods — utility methods tied to the interface.
public interface MathOps {
int compute(int a, int b);
static int max(int a, int b) {
return a > b ? a : b;
}
}
// Usage
System.out.println(MathOps.max(10, 20)); // 20Static methods are called on the interface name, not on an implementing class.
Functional Interface and Lambda
An interface with exactly one abstract method is called a functional interface. It can be used with a lambda expression — a shortcut for writing an anonymous class.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
The lambda (input) -> input.contains("@") is a short way to write:
new Validator() {
@Override
public boolean validate(String input) {
return input.contains("@");
}
};Same result, much less code.
Interface vs Abstract Class
| Interface | Abstract Class | |
|---|---|---|
| Multiple | A class can implement many | A class can extend only one |
| Fields | Only public static final (constants) | Regular instance fields |
| Constructor | No | Yes |
| Concrete methods | Only default and static | Yes, freely |
| Use when | Capability contract, unrelated classes | Shared code + shared state |
Rule of thumb:
- Does your type represent a capability or role? Use interface. (
Printable,Serializable,Comparable) - Does your type represent a family with shared code? Use abstract class. (
Animal→Dog,Cat)
Common Mistake 1: Forgetting to Implement All Methods
// COMPILE ERROR — exportToPDF() not implemented
public class Report implements Printable, Exportable {
public void print() { }
public void exportToCSV() { }
// exportToPDF() missing
}Common Mistake 2: Adding Instance Fields to Interface
// WRONG — instance fields not allowed
public interface Shape {
double pi = 3.14; // this is actually public static final — a constant
// int count; // this is implicitly static final too, may not be what you want
}Any field in an interface is automatically public static final. It is a constant, not an instance variable.
Common Mistake 3: Calling default Method Before Thinking
public interface Sortable {
int[] sort(int[] arr);
default void printSorted(int[] arr) {
int[] sorted = sort(arr); // calls the implementing class's version
for (int x : sorted) {
System.out.print(x + " ");
}
}
}default methods are not pure utilities — they call other interface methods. The actual implementation chosen depends on the class. This is powerful but easy to misunderstand.
Practice Task
Task: Create an interface Discountable with one method double getDiscountedPrice(double originalPrice). Create two classes:
StudentDiscount— 20% off (returnsoriginalPrice * 0.80)SeniorDiscount— 30% off (returnsoriginalPrice * 0.70)
In main, create an array Discountable[] with both types and print the discounted price of Rs.1000 for each.
Hint: Both classes implement Discountable. The array uses the interface type. Loop calls getDiscountedPrice(1000).
Solution:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
What to observe: Neither StudentDiscount nor SeniorDiscount are related to each other — one does not extend the other. They both just fulfill the Discountable contract. An interface groups unrelated classes by what they can do, not by what they are.
Continue the lesson path