以下是一些外行术语的描述以提供帮助:
接口:这是方法的集合。它们没有任何定义,它们的功能由实现它们的类决定。接口的一个示例是列表。所有列表(ArrayList、LinkedList)都有 add() 和 remove() 方法,因为它们实现了需要它们的 List 接口。
public interface List {
public void add (Object o);
public void remove (Object o);
}
public class MyList implements List {
public void add (Object o) {
// I must implement this method because of the interface List
}
public void remove (Object o) {
// I must implement this method because of the interface List
}
}
一个抽象类:这是一个部分完成的类。它与接口的不同之处在于它本身通常包含一些功能。但是,它(通常)缺少一些需要由 *extend*ing 子类定义的方法。这些方法被定义为抽象超类中的abstract方法。
public abstract class AbstractThing {
public void method1 (Object o) {
// This is a real method that does things
}
// Anyone who extends me must implement this
public abstract void method2 (Object o1, Object o2);
}
public class ActualThing extends AbstractThing implements List {
public void add (Object o) {
// I must implement this method because of the interface List
}
public void remove (Object o) {
// I must implement this method because of the interface List
}
public void method2 (Object o1, Object o2) {
// I must implement this method because of abstract method in
// the super class
}
implements 关键字被一个类用来指示它将实现接口 所需的方法。一个类可以实现任意数量的接口;唯一的要求是它为这些方法中的每一个提供定义。它也可以定义为 abstract 并依赖其子类来定义一些。然后,这些方法就像任何其他抽象类的抽象方法一样。
extends 关键字被一个类用来表示它将向某个现有类添加功能。如果父类是抽象的,则扩展类必须在父类中实现这些抽象方法中的任何一个。一个类只能扩展一个父类。
为什么这么复杂?接口很好,因为您可以假设实现类的某些功能。具体案例是List接口。大多数方法并不关心他们得到什么样的列表。他们只想知道该对象支持常见的列表方法。在声明中:
List<String> myList = new ArrayList();
您正在创建一个实际的 ArrayList 对象,但将其实现隐藏在 List 接口下。然后,稍后,如果您决定改用 LinkedList,则不必更改所有代码,因为它也实现了 List 接口。
还有几个 Java 定义的“接口集”(例如持久性)但没有实现。这允许第 3 方开发自己的实现(实际类),但由于它们都实现相同的通用接口,开发人员可以在不更改代码的情况下交换实现。