Abstract classes vs. interfaces in Java

·

2 min read

Abstract classes and interfaces are plentiful in Java code, and even in the Java Development Kit (JDK) itself. Each code element serves a fundamental purpose:

Interfaces are a kind of code contract, which must be implemented by a concrete class. Abstract classes are similar to normal classes, with the difference that they can include abstract methods, which are methods without a body. Abstract classes cannot be instantiated. Many developers believe that interfaces and abstract classes are similar, but they are actually quite different. Let's explore the main differences between them.

Table of Contents The essence of an interface When to use interfaces Overriding an interface method Constant variables Default methods The essence of an abstract class Abstract methods in abstract classes When to use abstract classes Differences between abstract classes and interfaces Take the Java code challenge! The essence of an interface At heart, an interface is a contract, so it depends on an implementation to serve its purpose. An interface can never have a state, so it cannot use mutable instance variables. An interface can only use final variables.

[ Also on InfoWorld: Does Java pass by reference or pass by value? ] When to use interfaces Interfaces are very useful for decoupling code and implementing polymorphism. We can see an example in the JDK, with the List interface:

public interface List extends Collection {

int size();
boolean isEmpty();
boolean add(E e);
E remove(int index);
void clear();

} As you likely noticed, this code is short and very descriptive. We can easily see the method signature, which we'll use to implement the methods in the interface using a concrete class.

The List interface contains a contract that can be implemented by the ArrayList, Vector, LinkedList, and other classes.

To use polymorphism, we can simply declare our variable type with List, and then choose any of the available instantiations. Here's an example:

Read more about the blog in-depth here.