Interfaces
An interface is a contract — a set of method signatures a class promises to implement.
Java
public interface Payable {
double amountDue(); // implicitly public abstract
}
public interface Refundable {
boolean refund();
}
public class Order implements Payable, Refundable {
private double total;
public Order(double total) { this.total = total; }
@Override public double amountDue() { return total; }
@Override public boolean refund() { return true; }
}A class implements many interfaces but extends one class — the main reason interfaces exist.
Programming to the interface
Java
public static void charge(Payable item) {
System.out.println("Charging NPR " + item.amountDue());
}This works for orders, invoices, subscriptions — anything satisfying the
contract, without charge() knowing the concrete type.
default and static methods
Since Java 8, interfaces may carry implementations:
Java
public interface Greeter {
String name();
default String greet() { // subclasses may override
return "Namaste, " + name();
}
static Greeter of(String n) { // factory helper
return () -> n;
}
}default exists mainly so new methods can be added to an interface
without breaking every existing implementation.
Abstract classes
An abstract class cannot be instantiated. It can hold state and constructors — unlike an interface — and can force subclasses to implement specific methods.
Java
public abstract class Shape {
protected String label;
protected Shape(String label) { this.label = label; }
public abstract double area(); // subclasses MUST implement
public String describe() { // shared implementation
return label + " has area " + area();
}
}
public class Circle extends Shape {
private final double r;
public Circle(double r) {
super("Circle");
this.r = r;
}
@Override public double area() { return Math.PI * r * r; }
}Which to use
| Interface | Abstract class | |
|---|---|---|
| Multiple per class | yes | no |
| Can hold fields/state | constants only | yes |
| Constructor | no | yes |
| Use when | defining a capability | sharing real code among close relatives |
Default to interfaces. Reach for an abstract class when subclasses genuinely share state and construction logic.