Sub topic 13
Distinguish Extending a Class from Implementing Interfaces
What this chapter covers
You already know how to write class Dog extends Animal. Java has a second way to relate types: an interface. This chapter explains what an interface is and how implements differs from extends. It also covers why a class can have only one superclass but many interfaces. This chapter assumes you know how to write a subclass, override a method, and use super.
What an interface is
An interface is a type that lists methods a class promises to provide. It describes what an object can do and says little about how it does it.
interface Swimmer {
void swim();
}The method swim() has no body. A class that implements Swimmer must supply one. You write implements instead of extends to say a class agrees to the promise.
Three facts about interfaces explain most of the differences from classes:
- Every method in an interface is
publicunless you say otherwise withprivate. Methods without a body are alsoabstract, even though you don't write that word. - An interface has no constructors. You cannot write
new Swimmer(). - An interface has no instance fields. Any field you declare in it is a constant:
public static final.
Extending a class versus implementing an interface
When a class extends another class, it inherits the superclass's fields, methods, and constructor chain. When a class implements an interface, it inherits no state. It only promises to provide the listed methods.
| Feature | `extends` a class | `implements` an interface |
|---|---|---|
| Keyword | `extends` | `implements` |
| How many allowed | One superclass | Any number of interfaces |
| Inherits fields (state) | Yes | No, only constants |
| Inherits method bodies | Yes | Only `default` methods |
| Has constructors | Yes, and `super(...)` calls one | No |
| Instance created with `new` | Yes | No, you need a class that implements it |
| Common meaning | "is a kind of" | "can do" |
Java allows only one superclass for each class. This rule is called single inheritance of classes. Interfaces avoid the problems that come with many superclasses, because they carry no instance state and no constructors.
Using both in one class
A class can do both. Write extends first, then implements, with interface names separated by commas.
interface Swimmer {
void swim();
}
interface Flyer {
void fly();
}
class Animal {
private final String name;
Animal(String name) {
this.name = name;
}
String getName() {
return name;
}
}
class Duck extends Animal implements Swimmer, Flyer {
Duck(String name) {
super(name);
}
@Override
public void swim() {
System.out.println(getName() + " paddles on the water");
}
@Override
public void fly() {
System.out.println(getName() + " flaps into the sky");
}
}
public class Main {
public static void main(String[] args) {
Duck duck = new Duck("Donald");
Animal animal = duck;
Swimmer swimmer = duck;
Flyer flyer = duck;
System.out.println(animal.getName());
swimmer.swim();
flyer.fly();
}
}Running this prints:
Donald
Donald paddles on the water
Donald flaps into the skyDuck gets its name field and getName() from Animal. The constructor uses super(name), exactly as in earlier chapters. Duck gets its obligations to implement swim() and fly() from the interfaces.
The same Duck object can be held in three different variables. Each variable's type decides which methods you can call through it. Through swimmer you can only call swim(). Through animal you can only call getName().
Here is the same structure as a diagram.
A solid arrow shows extends. A dashed arrow shows implements.
Polymorphism works with interfaces too
Dynamic dispatch, which you saw earlier, applies to interface types. If a variable has type Swimmer, Java runs the swim() of the actual object at runtime.
interface Swimmer {
void swim();
}
class Fish implements Swimmer {
@Override
public void swim() {
System.out.println("Fish glides");
}
}
class Human implements Swimmer {
@Override
public void swim() {
System.out.println("Human does freestyle");
}
}
public class Main {
public static void main(String[] args) {
Swimmer[] swimmers = { new Fish(), new Human() };
for (Swimmer s : swimmers) {
s.swim();
}
}
}Fish and Human share no superclass besides Object. The interface is the only link between them. That is a main reason to use interfaces: they let unrelated classes be treated alike.
Why `public` is required
Interface methods are public. When a class implements one, the implementing method must also be public. Leaving out public is a common mistake:
interface Swimmer {
void swim();
}
class Fish implements Swimmer {
@Override
void swim() { // compile error
System.out.println("Fish glides");
}
}The compiler reports that you are trying to assign weaker access than the interface method has. As you learned in the override rules chapter, an overriding method cannot reduce visibility. Package-private is weaker than public.
Default methods
An interface can also include a method with a body. You mark it default. Classes that implement the interface get that method for free, and they may override it.
interface Greeter {
String name();
default String greet() {
return "Hello, " + name();
}
}
class Student implements Greeter {
@Override
public String name() {
return "Maria";
}
}
public class Main {
public static void main(String[] args) {
Greeter g = new Student();
System.out.println(g.greet());
}
}This prints Hello, Maria. The default method calls name(), which the class provides. A default method can use other interface methods but cannot touch instance fields, because interfaces have none.
When two interfaces clash
Because a class can implement many interfaces, two of them may offer a default method with the same signature. Java will not guess. The class must override the method itself. Inside it, you can pick one version with InterfaceName.super.method().
interface Walker {
default String move() {
return "walk";
}
}
interface Runner {
default String move() {
return "run";
}
}
class Athlete implements Walker, Runner {
@Override
public String move() {
return Walker.super.move() + " then " + Runner.super.move();
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Athlete().move());
}
}This prints walk then run. This is a second use of the super keyword. In Walker.super.move(), the name before .super says which interface you mean. If you delete the move() method from Athlete, the code no longer compiles.
Interfaces can extend interfaces
An interface uses extends to build on other interfaces, and it may list several of them.
interface Swimmer {
void swim();
}
interface Flyer {
void fly();
}
interface Amphibious extends Swimmer, Flyer {
void land();
}A class that implements Amphibious must provide swim(), fly(), and land(). A class can never extend an interface, and an interface can never implement a class. Remember the pairs:
- class
extendsclass - class
implementsinterface - interface
extendsinterface
Abstract classes versus interfaces
An abstract class is also a type that cannot be created directly. How does it differ from an interface?
| Question | Abstract class | Interface |
|---|---|---|
| Can hold instance fields? | Yes | No |
| Can have constructors? | Yes | No |
| How many can a class use? | One | Many |
| Method access | Any level | Public (or private helpers) |
Pick an abstract class when subclasses share state or setup code. Pick an interface when you want to describe an ability that unrelated classes can offer.
Common mistakes
- Writing
implementsbeforeextends. The order must beextendsfirst. - Forgetting
publicon an implemented method. - Trying to extend two classes:
class A extends B, Cdoes not compile. - Expecting an interface to hold a changing value. Its fields are constants and cannot be reassigned.
- Forgetting to resolve a default method conflict.
Quick recap
- A class extends at most one class and may implement any number of interfaces.
- An interface describes abilities and has no constructors or instance state.
- Implementing methods must be
public. - Interface types work with polymorphism just like class types.
- Default methods give interfaces some behavior, and
Interface.super.method()resolves clashes.
Exercise
Will this code compile? If not, give two separate ways to fix it. class Robot {} class Machine {} interface Charger { void charge(); } class Droid extends Robot, Machine implements Charger { void charge() { } }
Show answer
It does not compile, for two reasons. First, a class can extend only one class, so extends Robot, Machine is illegal. Fix it by extending only one of them (for example extends Robot), or by turning Machine into an interface and using implements Machine, Charger. Second, charge() must be public because it implements an interface method. Fix it by writing public void charge() { }.
Exercise
Interfaces A and B both have a default method String id(). Class C implements A, B does not override id(). What happens, and how do you fix it so that id() returns the result of A's version?
Show answer
The class does not compile, because Java cannot choose between the two defaults. Fix it by overriding the method in C: public String id() { return A.super.id(); }.