Java Reference
In-Depth Information
Jack (a person) is walking.
Jeff (a duck) is walking.
John (a person) is walking.
How will your existing code change if you want to create a new class called
Cat
whose objects should have the
ability to walk? You will be surprised to see that you do not need to change anything in your existing code at all.
The
Cat
class should implement the
Walkable
interface and that is all. Listing 17-6 contains the code for the
Cat
class.
Listing 17-6.
A Cat Class
// Cat.java
package com.jdojo.interfaces;
public class Cat implements Walkable {
private String name;
public Cat(String name) {
this.name = name;
}
public void walk() {
System.out.println(name + " (a cat) is walking.");
}
}
You can use the following snippet of code to test the new
Cat
class with the existing code. Looking at the output,
you have made persons, ducks, and cats walk together by using the
Walkable
interface! This is one of the uses of an
interface in Java: it lets you put unrelated classes under one umbrella.
Walkable[] w = new Walkable[4];
w[0] = new Person("Jack");
w[1] = new Duck("Jeff");
w[2] = new Person("John");
w[3] = new Cat("Jace");
// Let everyone walk
Walkables.letThemWalk(w);
Jack (a person) is walking.
Jeff (a duck) is walking.
John (a person) is walking.
Jace (a cat) is walking.
You have achieved the objective of making different kinds of objects walk together using the interface construct.
So, what is an interface anyway?
An interface in Java defines a reference type to specify an abstract concept. It is implemented by classes that
provide an implementation of the concept. Prior to Java 8, an interface could contain only abstract methods, so it
represented a pure abstract concept. Java 8 allows an interface to have
static
and
default
methods that can also
contain implementation. Interfaces let you define a relationship between unrelated classes through the abstract
concept. In your example, the
Walkable
interface represented a concept that enabled you to treat the two unrelated
classes of
Person
and
Duck
the same way because both implemented the same concept.