DeployU
Interviews / Backend Engineering / What is the difference between an `interface` and an `abstract class` in Java?

What is the difference between an `interface` and an `abstract class` in Java?

conceptual Object-Oriented Programming Interactive Quiz Code Examples

The Scenario

You are a backend engineer at a fintech company. You are designing a new service that needs to model a variety of different financial instruments, such as stocks, bonds, and options.

You need to find a way to define a common set of behaviors for all financial instruments, but you are not sure whether to use an interface or an abstract class.

The Challenge

Explain the difference between an interface and an abstract class in Java. What are the pros and cons of each approach, and which one would you choose for this use case?

Wrong Approach

A junior engineer might think that they are interchangeable. They might not be aware of the difference in features or the design implications of choosing one over the other.

Right Approach

A senior engineer would be able to provide a detailed explanation of the differences between an `interface` and an `abstract class`. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in this use case.

Step 1: Understand the Key Differences

Featureinterfaceabstract class
MethodsCan only have abstract methods (before Java 8). Can have default and static methods (since Java 8).Can have both abstract and non-abstract methods.
FieldsCan only have public static final fields.Can have any type of field.
InheritanceA class can implement multiple interfaces.A class can only extend one abstract class.
ConstructorsCannot have a constructor.Can have a constructor.
Use CasesWhen you want to define a contract for a class.When you want to provide a base implementation for a class.

Step 2: Choose the Right Tool for the Job

For our use case, an interface is the best choice. This is because we want to define a common set of behaviors for all financial instruments, but we do not want to provide a base implementation. Each financial instrument will have its own unique implementation of the GetValue() method.

Step 3: Code Examples

Here are some code examples that show the difference between the two approaches:

interface:

public interface FinancialInstrument {
    double getValue();
}

public class Stock implements FinancialInstrument {
    private double price;

    public double getValue() {
        return price;
    }
}

abstract class:

public abstract class FinancialInstrument {
    public abstract double getValue();

    public String getCurrency() {
        return "USD";
    }
}

public class Stock extends FinancialInstrument {
    private double price;

    public double getValue() {
        return price;
    }
}

Practice Question

You want to create a new class that can be sorted. Which of the following would you use?