Java Reference
In-Depth Information
In your case, the only requirement for the Fish class is that it must have a swim() method, which accepts no
parameters and returns void as declared in the Swimmable interface. The following code defines two swim() methods in
the Fish class. The first one with no parameters implements the swim() method of the Swimmable interface. The second
one, swim(double distanceInYards) , has nothing to do with the Swimmable interface implementation by the Fish class.
public class Fish implements Swimmable {
// Override the swim() method in the Swimmable interface
public void swim() {
// More code goes here
}
// A valid method for the class Fish. This method declaration has nothing to do
// with the Swimmable interface's swim()
public void swim(double distanceInYards) {
// More code goes here
}
}
Listing 17-19 has the complete code for the Fish class. A Fish object will have a name, which is supplied in its
constructor. It implements the swim() method of Swimmable interface to print a message on the standard output.
Listing 17-19. Code for the Fish Class That Implements the Swimmable Interface
// Fish.java
package com.jdojo.interfaces;
public class Fish implements Swimmable {
private String name;
public Fish(String name) {
this.name = name;
}
public void swim() {
System.out.println(name + " (a fish) is swimming.");
}
}
How do you create an object of a class that implements an interface? You create an object of a class the same way
(by using the new operator with its constructor) whether it implements an interface or not. You can create an object of
the Fish class as
// Create an object of the Fish class
Fish fifi = new Fish("Fifi");
When you execute the statement new Fish("Fifi") , it creates an object in memory and that object's type is
Fish (the type defined by its class). When a class implements an interface, its object has one more type, which is the
type defined by the implemented interface. In your case, the object created by executing has two types: Fish and
Swimmable . In fact it has a third type, too, which is the Object type by virtue of the Fish class inheriting the Object
 
Search WWH ::




Custom Search