Skip to lesson

Abstract Class vs Interface

In a Java interview, "abstract class or interface?" is a design question, not a definition. The interviewer wants the differences, the Java 8 and 9 interface features, and a clear reason for choosing one.

Comparison: state, constructors, inheritance, access

An abstract class is a class declared abstract that cannot be instantiated. It can hold fields, constructors, concrete methods and abstract methods that subclasses must implement.

An interface is the other half: a list of methods a class promises to provide with implements. The code shows how the two differ in state, constructors and access.

Left, a family: the abstract class Account holds int balance and withdraw(); Savings and Current extend it, and each is an Account. Right, an ability: the interface Shareable lists share(); the unrelated classes Photo, Doc and Map all implement it.

Example 1 · The same idea as an abstract class and as an interface

AbstractVsInterface.javaJava
abstract class Shape {    private final String label;    private static int created;
    protected Shape(String label) {        this.label = label;        created++;    }
    abstract double area();
    String describe() {        return label + " with area " + String.format("%.2f", area());    }
    static int created() {        return created;    }}
interface Printable {    int MAX_COPIES = 3;                         // public static final    String print();                             // public abstract}
class Circle extends Shape implements Printable {    private final double r;
    Circle(double r) {        super("Circle");        this.r = r;    }
    double area() {        return Math.PI * r * r;    }
    public String print() {        return "[" + describe() + "]";    }}
public class AbstractVsInterface {    public static void main(String[] args) {        Circle c = new Circle(2);        System.out.println(c.describe());        System.out.println(c.print() + " up to " + Printable.MAX_COPIES + " copies");        System.out.println("Shapes created: " + Shape.created());        // new Shape("x");   // error: Shape is abstract; cannot be instantiated    }}
Output
Circle with area 12.57
[Circle with area 12.57] up to 3 copies
Shapes created: 1

What this code does

  • Shape uses what only an abstract class can have: a private instance field, a constructor called through super, and a protected member. Circle extends it and also implements Printable.
  • Printable only declares a capability and a constant; its print() is implicitly public abstract, which is why Circle.print() must be public.

Must know:

  • state: abstract class can have instance fields; interface fields are only public static final constants
  • constructors: abstract class yes (called via super); interface no
  • inheritance: a class extends one abstract class but implements many interfaces; an interface can extend many interfaces
  • access: abstract class members can be private, protected or package-private; interface members are public (except private helper methods)

default, static and private interface methods

A default method is an interface method with a body, marked default. Implementing classes inherit it and may override it. Java 8 added it so interfaces could grow without breaking existing classes.

Java 8 also added static interface methods, and Java 9 added private ones. One Discount interface in the code uses all three kinds.

Example 2 · default, static and private interface methods

InterfaceMethods.javaJava
interface Discount {    int percent();
    default int apply(int price) {        return price - cut(price);    }
    default String label(int price) {        return "Save Rs " + cut(price);    }
    private int cut(int price) {        return price * percent() / 100;    }
    static Discount festival() {                      // Java 8 static factory        return () -> 20;    }}
class StudentDiscount implements Discount {    public int percent() {        return 10;    }
    @Override    public String label(int price) {                  // a default can be overridden        return "Student offer: " + Discount.super.label(price);    }}
public class InterfaceMethods {    public static void main(String[] args) {        Discount student = new StudentDiscount();        Discount fest = Discount.festival();          // called on the interface        System.out.println(student.apply(1500) + ", " + student.label(1500));        System.out.println(fest.apply(1500) + ", " + fest.label(1500));    }}
Output
1350, Student offer: Save Rs 150
1200, Save Rs 300

What this code does

  • apply and label are default methods inherited by every Discount; both reuse the private helper cut, which no implementing class can see.
  • Discount.festival() is a static method called through the interface name; because Discount has one abstract method, a lambda () -> 20 can implement it.

Static methods are helpers called through the interface name; private methods share code between default methods and stay hidden from implementing classes.

Default methods exist to evolve interfaces: Collection gained stream() without breaking existing classes. Static interface methods are not inherited: Comparator.comparing(...) works, but calling it through an implementing class does not compile.

Find the bug

Which line does not compile?

Tap the line the Java compiler rejects.

A static method of an interface is called in two ways.

Round 1 of 3

Diamond conflict with two default methods

If a class implements two interfaces that both provide the same default method, Java cannot choose, and the class does not compile. The code resolves the clash and shows two rules that settle other cases.

Example 3 · Resolving two conflicting default methods

DefaultConflict.javaJava
interface Upi {    default String receipt() {        return "UPI receipt";    }}
interface Card {    default String receipt() {        return "Card slip";    }}
class SplitPayment implements Upi, Card {    @Override    public String receipt() {                       // required, or the class does not compile        return Upi.super.receipt() + " + " + Card.super.receipt();    }}
class Base {    public String receipt() {        return "Base class receipt";    }}
class ShopPayment extends Base implements Upi {     // class wins over interface default}
public class DefaultConflict {    public static void main(String[] args) {        System.out.println(new SplitPayment().receipt());        System.out.println(new ShopPayment().receipt());    }}
Output
UPI receipt + Card slip
Base class receipt

What this code does

  • Without the override, SplitPayment fails with "types Upi and Card are incompatible; class SplitPayment inherits unrelated defaults for receipt()". Upi.super.receipt() calls one parent's default explicitly.
  • ShopPayment gets receipt() from both Base and Upi; the class method wins, so no override is needed.

The fix is to override the method in the class and decide: return your own result, or call one parent with Upi.super.receipt(). Two rules settle most other cases first: a method from a superclass beats an interface default ("class wins"), and a more specific sub-interface beats its parent.

Without the override, javac reports: types Upi and Card are incompatible; class Pay inherits unrelated defaults for receipt() from types Upi and Card.

Fix the error

Fix the interface error

Read the real javac error, then pick the line that fixes it.

Round 1 of 2

Split implements two interfaces that both have receipt().

interface Upi {
default String receipt() { return "UPI"; }
}
interface Card {
default String receipt() { return "Card"; }
}
class Split implements Upi, Card { }

Error

Round1.java:7: error: types Upi and Card are incompatible;
class Split implements Upi, Card { }
^
  class Split inherits unrelated defaults for receipt() from types Upi and Card

When to choose which: the payment example

The template method is a pattern in which a base class fixes the steps of an algorithm in a final method and leaves some steps abstract for subclasses to fill in.

The usual design answer combines both: an interface for the capability, an abstract base class for the shared steps. The code builds a small payment system that way.

Example 4 · Payment design: interface + abstract base + concrete types

PaymentDesign.javaJava
import java.util.List;
interface Payment {    String pay(int amount);}
abstract class BasePayment implements Payment {    private final String method;
    protected BasePayment(String method) {        this.method = method;    }
    @Override    public final String pay(int amount) {             // template method: fixed steps        if (amount <= 0) {            return method + ": invalid amount";        }        String ref = charge(amount);                  // the step each type supplies        return method + ": Rs " + amount + " paid, ref " + ref;    }
    protected abstract String charge(int amount);}
class UpiPayment extends BasePayment {    UpiPayment() { super("UPI"); }    protected String charge(int amount) { return "UPI" + (1000 + amount); }}
class CardPayment extends BasePayment {    CardPayment() { super("Card"); }    protected String charge(int amount) { return "CARD" + (2000 + amount); }}
public class PaymentDesign {    public static void main(String[] args) {        List<Payment> payments = List.of(new UpiPayment(), new CardPayment(), new UpiPayment());        int[] amounts = {250, 1200, 0};        for (int i = 0; i < payments.size(); i++) {            System.out.println(payments.get(i).pay(amounts[i]));        }    }}
Output
UPI: Rs 250 paid, ref UPI1250
Card: Rs 1200 paid, ref CARD3200
UPI: invalid amount

What this code does

  • Callers depend only on the Payment interface; the abstract BasePayment holds the shared state (method) and the fixed validation steps in a final template method.
  • Each concrete class writes only its own charge step. A wallet payment later is one small new class, with no change to callers.

Choose an interface for a capability that different kinds of classes share, or when a class needs several types: Payment, Refundable, Comparable. Choose an abstract class when closely related classes share fields, constructors and code, especially a fixed sequence of steps.

Model answer: "Payment is an interface, because UPI, card and wallet payments only share the ability to pay. Their common steps, validating the amount and logging, go into an abstract BasePayment that implements Payment. Each concrete type extends BasePayment and implements only its own charge step."

Order of execution

Build the payment design

Put the steps of the model answer in the order you would say them.

Functional and marker interfaces

A functional interface has exactly one abstract method, so a lambda can implement it. Runnable, Comparator and Predicate are examples; @FunctionalInterface makes the compiler enforce the rule.

Two special kinds of interface come up often: one with a single abstract method, and one with no methods at all. The code shows both.

Example 5 · A functional interface and a marker interface

SpecialInterfaces.javaJava
import java.io.Serializable;
@FunctionalInterfaceinterface FeeRule {    int fee(int marks);                       // exactly one abstract method
    default FeeRule withCap(int cap) {        // defaults do not count        return marks -> Math.min(fee(marks), cap);    }}
class Receipt implements Serializable {       // marker: no methods to implement    final String id;    Receipt(String id) { this.id = id; }}
public class SpecialInterfaces {    public static void main(String[] args) {        FeeRule byMarks = marks -> marks >= 90 ? 0 : 50000;        FeeRule capped = byMarks.withCap(30000);        System.out.println(byMarks.fee(95) + " " + byMarks.fee(70) + " " + capped.fee(70));
        Object r = new Receipt("R-101");        System.out.println("Serializable? " + (r instanceof Serializable));        Runnable hello = () -> System.out.println("Runnable is a functional interface too");        hello.run();    }}
Output
0 50000 30000
Serializable? true
Runnable is a functional interface too

What this code does

  • FeeRule has one abstract method, so lambdas implement it; @FunctionalInterface would make adding a second abstract method a compile error. The default withCap builds a new rule from the old one.
  • Receipt implements Serializable, which has no methods; it only marks the class, and code checks it with instanceof.

Default and static methods do not count towards the single abstract method. A marker interface has no methods and only tags a class: Serializable allows Java serialisation, Cloneable allows Object.clone(), RandomAccess signals fast index access. Code checks for it with instanceof. Annotations are the modern way to attach such markers.

Predict the output

Which default wins?

Predict the exact output, then read the rule.

Round 1 of 3

A superclass method and an interface default have the same name.

interface Greeter {
default String hello() { return "interface"; }
}
class Base {
public String hello() { return "class"; }
}
class Impl extends Base implements Greeter { }
public class Round1 {
public static void main(String[] args) {
System.out.println(new Impl().hello());
}
}

Next step

Check your understanding

12 quick questions