Interfaces against abstract classes

Both an abstract class and an interface describe something a class must provide, and both are types. The differences are concrete: an abstract class has fields and constructors, an interface has neither; a class may extend one class and implement any number of interfaces; and an interface may carry a default body, which an abstract class does not need a keyword for. This lesson puts a program under each idea and ends with the table to choose by.

An abstract class

Animal holds the name, a constructor that sets it, a concrete method that uses it and an abstract method the subclasses supply. The state and the constructor are the part an interface cannot have:

public class AbstractDemo { public static void main(String[] args) { Animal[] animals = {new Dog("Rex"), new Cat("Mia")}; for (Animal animal : animals) { System.out.println(animal.describe()); } } } abstract class Animal { private final String name; Animal(String name) { this.name = name; } String name() { return name; } abstract String sound(); String describe() { return name + " says " + sound(); } } class Dog extends Animal { Dog(String name) { super(name); } @Override String sound() { return "woof"; } } class Cat extends Animal { Cat(String name) { super(name); } @Override String sound() { return "meow"; } }

javac -Xlint:all AbstractDemo.java
java AbstractDemo

Rex says woof
Mia says meow

The template method of lesson 050 is in describe: it fixes the shape of the sentence and calls the abstract method for the variable part. A subclass cannot change the sentence, and it must supply the sound.

An interface

The same three kinds of member in an interface: a constant, an abstract method, and two bodies, one default for the implementors and one static for callers. A field of an interface is always public static final, whether the words are written or not:

public class InterfaceDemo { public static void main(String[] args) { Greeter greeter = new English(); System.out.println(greeter.greet("Ada")); System.out.println(greeter.shout("Ada")); System.out.println(Greeter.VERSION); System.out.println(Greeter.plain("Ada")); } } interface Greeter { String VERSION = "1.0"; String greet(String name); default String shout(String name) { return greet(name).toUpperCase(); } static String plain(String name) { return "hello " + name; } } class English implements Greeter { @Override public String greet(String name) { return "hi " + name; } }

javac -Xlint:all InterfaceDemo.java
java InterfaceDemo

hi Ada
HI ADA
1.0
hello Ada

shout is inherited from the interface and calls the implementation the class supplied; plain is a static method and is called on the interface name, never on an object. The methods of English are public, because an interface method is public and an implementation may not narrow it.

A class with both

A document has a title, which is state, and it is a report, which is a kind of document; it is also printable and summarisable, which are promises any class may make. So it extends one class and implements two interfaces:

public class Both { public static void main(String[] args) { Report report = new Report("Q3"); System.out.println(report.title()); System.out.println(report.render()); System.out.println(report.summary()); report.print(); } } abstract class Document { private final String title; Document(String title) { this.title = title; } String title() { return title; } abstract String render(); } interface Printable { void print(); } interface Summarisable { String summary(); } class Report extends Document implements Printable, Summarisable { Report(String title) { super(title); } @Override String render() { return "report " + title(); } @Override public void print() { System.out.println(render()); } @Override public String summary() { return title() + " (report)"; } }

javac -Xlint:all Both.java
java Both

Q3
report Q3
Q3 (report)
report Q3

The last two lines are the same text from two paths: print calls render and writes it, and summary builds its own sentence. A method that takes a Printable accepts a Report and any other class that promises the same method, whatever its superclass is.

One superclass, many interfaces

The rule that decides most designs is this one, and the compiler states it in the plainest way it has: after the first type in an extends clause, the comma is a syntax error:

public class Two { public static void main(String[] args) { C c = new C(); System.out.println(c); } } class A { } class B { } class C extends A, B { }

javac -Xlint:all Two.java

Two.java:14: error: '{' expected
class C extends A, B {
^
1 error

The reason is the constructor chain: a class constructor calls exactly one superclass constructor, and two superclasses would need two calls and two copies of the state. An interface has no state and no constructor, so a class can implement as many as it likes, which is the multiple inheritance of type the next lesson uses.

The table

The choice, in the order the questions come up:

State or a constructor: an abstract class, because an interface has neither. A promise several unrelated classes can make: an interface, because a class has only one superclass. A default body for the promise: both can, an interface with default and an abstract class with a concrete method. A constant: both, though an interface constant is public and part of the type. An evolution that adds a method: an interface with a default body, since adding an abstract method breaks every implementor.

The usual shape of a library is both at once: an interface is the type the callers see, and an abstract class is an optional skeleton that implements the boring parts. java.util.List and AbstractList are the pair, and the collection part of this course uses both.

Exercises

  1. Give Greeter a second default method that returns the greeting twice and print it from English.
  2. Add a weight() method to Animal with a body and make Cat override it.
  3. Make Report implement a third interface with one method and call it from main.
  4. Try to put a field with a setter into an interface and read the error.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which of the two may hold state?

    Answer

    An abstract class, in instance fields

    An interface has no instance fields, so all its state must live in the implementing class.

  2. How many classes may a Java class extend?

    Answer

    One

    A constructor calls one superclass constructor, so there is one superclass.

  3. How many interfaces may a class implement?

    Answer

    Any number

    Interfaces carry no state, so several of them need no conflicting constructor calls.

  4. What does this program print? public class Q1 { public static void main(String[] args) { A a = new B(); System.out.println(a.text()); } } abstract class A { String text() { return "a" + extra(); } abstract String extra(); } class B extends A { String extra() { return "b"; } }

    Answer

    ab

    The concrete method calls the abstract one, and the subclass supplies it.

  5. What does this program print? public class Q2 { public static void main(String[] args) { I i = new C(); System.out.println(i.text()); System.out.println(I.VALUE); } } interface I { int VALUE = 7; default String text() { return "d"; } } class C implements I { }

    Answer

    d then 7

    The default method is inherited, and the interface constant is public and static.

  6. What does this program print? public class Q3 { public static void main(String[] args) { C c = new C(); System.out.println(c.a() + c.b()); } } interface A { default String a() { return "a"; } } interface B { default String b() { return "b"; } } class C implements A, B { }

    Answer

    ab

    Two different signatures, so both defaults are inherited with no conflict.

  7. What is the first line of the compiler output for this program? public class Q4 { public static void main(String[] args) { C c = new C(); System.out.println(c); } } class A { } class B { } class C extends A, B { }

    Answer

    error: '{' expected

    Only one type may follow extends; the comma is a syntax error.

  8. What does this program print? public class Q5 { public static void main(String[] args) { P p = new C(); p.print(); System.out.println(p instanceof D); } } interface P { void print(); } abstract class D { } class C extends D implements P { public void print() { System.out.println("c"); } }

    Answer

    c then true

    C is a D by inheritance and a P by implementation, so both types hold the object.

  9. Which is the safer way to add a method to an interface used by many classes?

    Answer

    Add it with a default body

    A default body keeps every existing implementor compiling.

  10. What may an interface field be?

    Answer

    public static final, written or not

    The modifiers are implied, so every interface field is a constant.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev

Banner image