1、接口的创建
---声明接口
---在接口主体中创建抽象方法
---以扩展名.java保存文件
---编译接口
2、实现接口的步骤
---声明类,在加快名之前使用implement关键字
---实现所有在参加接口时声明的抽象类
---以扩展名.java保存文件
---编译Applet或应用程序
3、在创建和实现接口时要遵循的一些规则:
---接口可以用public声明,因此可以在包外被实现
---接口并不能被完全视为java不支持的多重继承的代替品
---声明接口中的成员时,不能用private和protected访问修饰符
---接口中的常量声明只能是public、static和final
---接口声明的所有方法只能是public和abstract
---一个类可以实现所需的任意多的接口,接口名之间用逗号分隔
注意:如果父类已经实现了一个接口,它的子类就不需要再使用implement关键字。
示例一
interface
one
...
{
public void xx();
}
interface two
extends
one
...
{
public void yy();
}
class cl1 implements
one
... {
public void xx()
...{
System.out.println("The function xx of class cl1 implements interface one");
}
public void yy()
...{
System.out.println("Original yy in class but not in interface");
}
}
class cl2 implements two
... {
public void xx()
...{
System.out.println("The function xx of class cl2 implements interface two");
}
public void yy()
...{
System.out.println("The function yy of class cl2 implements interface two");
}
}
示例二
DisplayInterface.java
public interface DisplayInterface
... {
public String GetDisplayText();//no implementation of this method
}
ex13.java
// This Applet implements the method delared in the interface
import java.awt. * ;
import java.applet. * ;
import java.lang. * ;
public class ex13 extends
Applet
implements
DisplayInterface
... {
public void paint(Graphics g)
...{
String str=GetDisplayText();
g.drawString(str,80,100);
}
public String GetDisplayText()
...{
return "Display Text";
}
}
first_applet.html
< applet code ="ex13.class" width =300 height
=200
>
</ applet >
示例二的实现:
1、把上面三个文件都放进C:/think/interfaces文件夹里
2、选择 开始-程序-附件-命令提示符打开一个命令提示符窗口。键入cd C:/think/interfaces回车(注意cd后有个空格),再键入javac ex13.java回车,如果程序不出错的话,接着键入appletviewer first_applet.html回车。
3、就可以看到弹出的applet小窗口。