Java - Interfaces & Abstract Classes
Interfaces & Abstract Classes
Interfaces
interface Shape {
double area();
default String unit() { return "sq"; } // default method (Java 8+)
static Shape square(double a) { return () -> a * a; } // static method
}
Shape s = Shape.square(3);
System.out.println(s.area());
Functional Interfaces
@FunctionalInterface interface Combiner { int apply(int a, int b); }
Combiner c = (a,b) -> a + b;
int r = c.apply(2,3);
Abstract Classes
Can hold state and partial implementations; subclasses fill in the abstract pieces.
abstract class Polygon implements Shape {
protected final int sides;
Polygon(int s) { this.sides = s; }
}
class Square extends Polygon {
private final double a;
Square(double a){ super(4); this.a = a; }
public double area(){ return a*a; }
}
When to Use Which
- Use interfaces to define capabilities and allow multiple inheritance of types.
- Use abstract classes when you need shared state/behavior with controlled extension points.
Default method conflicts: implementor must resolve if two interfaces define the same default method signature.
Try it
- Implement a
Shape
interface with a lambda for a square and testarea()
. - Create an abstract class with a protected field and a concrete subclass that uses it.