Java Reference
In-Depth Information
There is no limit on the maximum number of interfaces implemented by a class. When a class implements an
interface, its objects get an additional type. If a class implements multiple interfaces, its objects get as many new
types as the number of implemented interfaces. Consider the object of the
ArithOps
class, which can be created
by executing
new ArithOps()
. The object of the
ArithOps
class gets two additional types, which are
Adder
and
Subtractor
. The following snippet of code shows the result of the object of the
ArithOps
class getting two new types.
You can treat an object of
ArithOps
as
ArithOps
type,
Adder
type, or
Subtractor
type. Of course, every object in Java
can always be treated as an
Object
type.
ArithOps a = new ArithOps();
Adder b = new ArithOps();
Subtractor c = new ArithOps();
b = a;
c = a;
Let's look at a more concrete and complete example. You already have two interfaces,
Walkable
and
Swimmable
.
If a class implements the
Walkable
interface, it must provide the implementation for the
walk()
method. If you want
an object of a class to be treated as the
Walkable
type, the class would implement the
Walkable
interface. The same
argument goes for the
Swimmable
interface. If a class implements both interfaces,
Walkable
and
Swimmable
, its objects
can be treated as a
Walkable
type as well as a
Swimmable
type. The only thing that the class must do is to provide
implementation for both the
walk()
and
swim()
methods. Let's create a
Turtle
class, which implements both of these
interfaces. A
Turtle
object will have ability to walk as well as swim.
Listing 17-21 has the code for the
Turtle
class. A turtle can bite too. You have added this behavior to the
Turtle
objects by adding a
bite()
method to the
Turtle
class. Note that adding the
bite()
method to the
Turtle
class has
nothing to do with implementations of two interfaces. A class, which implements interfaces, can have any number of
additional methods of its own.
Listing 17-21.
A Turtle Class, Which Implements the Walkable and Swimmable Interfaces
// Turtle.java
package com.jdojo.interfaces;
public class Turtle implements Walkable, Swimmable{
private String name;
public Turtle(String name) {
this.name = name;
}
// Adding a bite() method to the Turtle class
public void bite() {
System.out.println(name + " (a turtle) is biting.");
}
// Implementation for the walk() method of the Walkable interface
public void walk() {
System.out.println(name + " (a turtle) is walking.");
}
// Implementation for the swim() method of the Swimmable interface
public void swim() {
System.out.println(name + " (a turtle) is swimming.");
}
}