Tools
Log in
English

Learn to codeJava

Java abstraction

Based on Java 17isBlank·strip · Java 11+

Java interface vs abstract class, with a notice sender example and a table.

In one line

Decide only what has to be done and leave how to do it to later classes. In Java you do this with interface and abstract class.

Why you need it

Writing email and SMS notice code separately means repeating the same steps in each channel: drop blank messages, trim spaces, record how many were sent. Forget a check in one channel and only that channel sends empty notices.

The Notifier interface only promises "can send", and BaseNotifier writes the shared steps once. Each channel class fills in just deliver, the part that actually sends.

Everyday picture

Every country fixes the shape of its wall sockets. A company making appliances only has to match that shape (the interface); what happens inside is up to each maker. An abstract class is a half-built kit: "the power unit is already fitted, just build the feature part and attach it."

Example code

Main.java · 55 lines
import java.util.ArrayList;import java.util.List; interface Notifier {    boolean send(String to, String message);} abstract class BaseNotifier implements Notifier {    private int sent;     @Override    public final boolean send(String to, String message) {        if (message.isBlank()) {            return false;        }        deliver(to, message.strip());        sent++;        return true;    }     int sentCount() {        return sent;    }     protected abstract void deliver(String to, String text);} class EmailNotifier extends BaseNotifier {    @Override    protected void deliver(String to, String text) {        System.out.println("[email] " + to + " <- " + text);    }} class SmsNotifier extends BaseNotifier {    @Override    protected void deliver(String to, String text) {        String cut = text.length() > 20 ? text.substring(0, 20) + "..." : text;        System.out.println("[sms] " + to + " <- " + cut);    }} public class Main {    public static void main(String[] args) {        EmailNotifier email = new EmailNotifier();        List<Notifier> channels = new ArrayList<>();        channels.add(email);        channels.add(new SmsNotifier());        for (Notifier n : channels) {            n.send("mina", "  Your order has shipped today  ");            n.send("mina", "   ");        }        System.out.println("email sent: " + email.sentCount());    }}

interface vs abstract class

interfaceabstract class
Create with newXX
Per-object fieldsXO
Methods with a bodydefault and static onlyO
ConstructorsXO
How many a class can takemany, with implementsone, with extends

Any field written in an interface becomes a public static final constant.

When to use it

  • You name a job before its implementations exist (storage, payment, notices, file reading) → interface
  • Children share the same order of steps and fields and differ in one or two steps → abstract class
  • You want to swap in a fake implementation for tests → interface

A class has one parent class but can implements many interfaces. If you are unsure, start with an interface.

isBlank and strip are string methods added in Java 11.

Common mistakes

Creating an abstract class with new

BaseNotifier has no body for deliver, so it cannot be used as it is. Create a child class that fills in every abstract method.

Wrong

public class Main {    public static void main(String[] args) {        Notifier n = new BaseNotifier();    }}

What javac sayserror: BaseNotifier is abstract; cannot be instantiated

Fixed

public class Main {    public static void main(String[] args) {        Notifier n = new EmailNotifier();        n.send("mina", "hello");    }}

When you run it[email] mina <- hello

Filling the abstract method under another name

You wrote push, but the parent asks for deliver. Match the name and parameters exactly and add @Override.

Wrong

class PushNotifier extends BaseNotifier {    protected void push(String to, String text) {        System.out.println("[push] " + to + " <- " + text);    }}

What javac sayserror: PushNotifier is not abstract and does not override abstract method deliver(String,String) in BaseNotifier

Fixed

class PushNotifier extends BaseNotifier {    @Override    protected void deliver(String to, String text) {        System.out.println("[push] " + to + " <- " + text);    }}

Keeping changing state in an interface

Interface fields are automatically static final constants, so they cannot change. Put per-object values in a private field of an abstract or concrete class.

Wrong

interface Notifier {    int sent = 0;     default void countUp() {        sent++;    }}

What javac sayserror: cannot assign a value to final variable sent

Fixed

interface Notifier {    boolean send(String to, String message);} abstract class BaseNotifier implements Notifier {    private int sent;     protected void countUp() {        sent++;    }}

Check yourself

Question 1

Which one can hold a per-object field and pass it to children?

Show the answer

Answer: 2. abstract class Fields written in an interface are all public static final constants. Per-object values belong in an abstract class.

Question 2

Using the example classes, what does this print?

public class Main {    public static void main(String[] args) {        Notifier n = new SmsNotifier();        System.out.println(n.send("joon", " "));    }}

Show the answer

Answer: 2. false send is final, so the SMS channel also runs the blank check first. A single space is blank, so only false is printed.

Questions people ask

Should I start with an interface or an abstract class?

Start with an interface when you only name the job. Add an abstract class once several implementations share the same steps or fields.

Can an interface have methods with a body?

Since Java 8, default and static methods are allowed. Per-object fields are still not.

Can I create an object from an abstract class?

Not directly with new. Create a subclass that fills in every abstract method.