Java Reference
In-Depth Information
public Person(String name) {
this.name = name;
}
public void walk() {
System.out.println(name + " (a person) is walking.");
}
}
Listing 17-3.
The Revised Duck Class, Which Implements the Walkable Interface
// Duck.java
package com.jdojo.interfaces;
public class Duck
implements Walkable
{
private String name;
public Duck(String name) {
this.name = name;
}
public void walk() {
System.out.println(name + " (a duck) is walking.");
}
}
Note that the declarations of the revised classes have a minor difference from their original declarations. Both
of them have a new
implements Walkable
clause added to their declarations. Since both of them implement the
Walkable
interface, they must provide the implementation for the
walk()
method as declared in the
Walkable
interface. You did not have to define a fresh
walk()
method as you had it implemented from the very beginning.
If these classes did not have a
walk()
method, you had to add it to them at this stage.
Before you revise the code for your
Walkables
class, let's look at other things that you can do with the
Walkable
interface. Like a class, an interface defines a new reference type. When you define a class, it defines a new reference
type and it lets you declare variable of that type. Similarly, when you define a new interface (e.g.
Walkable
), you can
define a reference variable of the new interface type. The variable scope could be local, instance, static, or a method
parameter. The following declaration is valid:
Walkable w; // w is a reference variable of type Walkable
You cannot create an object of an interface type. The following code is invalid:
new Walkable(); // A compile-time error
You can create an object of only a class type. However, an interface type variable can refer to any object whose
class implements that interface. Because the
Person
and
Duck
classes implement the
Walkable
interface, a reference
variable of the
Walkable
type can refer to an object of these classes.
Walkable w1 = new Person("Jack"); // OK
Walkable w2 = new Duck("Jeff"); // OK
// A compile-time error as the Object class does not implement the Walkable interface
Walkable w3 = new Object();