implements一般是实现接口。
extends 是继承类。
接口一般是只有方法声明没有定义的,
那么java特别指出实现接口是有道理的,因为继承就有感觉是父类已经实现了方法,而接口恰恰是没有实现自己的方法,仅仅有声明,也就是一个方法头没有方法体。因此你可以理解成接口是子类实现其方法声明而不是继承其方法。
但是一般类的方法可以有方法体,那么叫继承比较合理。
引入包可以使用里面非接口的一切实现的类。那么是不是实现接口,这个你自己决定,如果想用到那么你不是实现,是不能调用这个接口的,因为接口就是个规范,是个没方法体的方法声明集合。我来举个例子吧:接口可以比作协议,比如我说 一个协议是“杀人”那么这个接口你可以用 砍刀 去实现,至于怎么杀 砍刀 可以去实现,当然你也可以用抢来实现杀人接口,但是你不能用杀人接口去杀人,因为杀人接口只不过是个功能说明,是个协议,具体怎么干,还要看他的实现类。
那么一个包里面如果有接口,你可以不实现。这个不影响你使用其他类。
Java中使用接口
pulic interface DataOutput {
void writeBoolean(boolean value) throws IOException;
void writeByte(int value) throws IOException;
void writeChar(int value) throws IOException;
void writeShort(int value) throws IOException;
void writeInt(int value) throws IOException;
...
}
创建一个实现这个接口的类 需要使用关键字 implements:
public class DateOutputStream extends FilterOutputStream implements DataOutput {
public final void writeBoolean (Boolean value) throws IOException {
write (value ? 1 : 0);
}
...
}
该类声明并具体实现了接口中列出的每一个方法。漏掉任何一个方法都会导致在编译时显示错误。
下面是Java编译器在发现一个接口错误时可能产生的输出信息
-----------------------------
MyClass should be delared abstract; it does not define writeBoolean(boolean) in MyClass.
-----------------------------
PHP
interface MyInterface {
public function interfaceMethod($argumentOne,$argumentTwo);
}
class MyClass impements MyInterface {
public function interfaceMethod($argumentOne,$argumentTwo) {
return $argumentOne . $argumentTwo;
}
}
class BadClass impements MyInterface {
// No method declarations .
}
/**
BadClass causes this error at run-time:
Fatal error: Class BadClass contains 1 abstract methods and must therefore be declared abstract (MyInterface::InterfaceMethod)
*/
C#
interface MyInterface {
string interfaceMethod(string argumentOne,string argumentTwo);
}
class MyClass : MyInterface {
public string interfaceMethod(string argumentOne,string argumentTwo) {
return argumentOne + argumentTwo;
}
}
class BadClass : MyInterface {
// No method declarations .
}
// BadClass causes this error at compile-time:
// BadClass does not implement interface member MyInterface.interfaceMethod()