Implements means that it takes on the designated behavior that the interface specifies. Consider the following interface:
public interface ISpeak
{
public String talk();
}
public class Dog implements ISpeak
{
public String talk()
{
return "bark!";
}
}
public class Cat implements ISpeak
{
public String talk()
{
return "meow!";
}
}
Both the Cat
and Dog
class implement the ISpeak
interface.
What's great about interfaces is that we can now refer to instances of this class through the ISpeak
interface. Consider the following example:
Dog dog = new Dog();
Cat cat = new Cat();
List<ISpeak> animalsThatTalk = new ArrayList<ISpeak>();
animalsThatTalk.add(dog);
animalsThatTalk.add(cat);
for (ISpeak ispeak : animalsThatTalk)
{
System.out.println(ispeak.talk());
}
The output for this loop would be:
bark!
meow!
Interface provide a means to interact with classes in a generic way based upon the things they do without exposing what the implementing classes are.
One of the most common interfaces used in Java, for example, is Comparable
. If your object implements this interface, you can write an implementation that consumers can use to sort your objects.
For example:
public class Person implements Comparable<Person>
{
private String firstName;
private String lastName;
// Getters/Setters
public int compareTo(Person p)
{
return this.lastName.compareTo(p.getLastName());
}
}
Now consider this code:
// Some code in other class
List<Person> people = getPeopleList();
Collections.sort(people);
What this code did was provide a natural ordering to the Person
class. Because we implemented the Comparable
interface, we were able to leverage the Collections.sort()
method to sort our List
of Person
objects by its natural ordering, in this case, by last name.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…