Java接口的创建与实现

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小窗口。
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值