示例代码:
接口:使用interface关键字修饰,类似与抽象类,接口里的方法没有方法体,接口提供一组标准,
- public interface ICharQueue { //定义接口接口
- void put(char ch); //接口中的方法
- char get();
- }
- class FixedQueue implements ICharQueue{ //使用implement关键字继承接口
- private char[] q;
- private int putid,getid;
- public FixedQueue(int size) { //构造方法
- q = new char[size];
- putid = getid = 0;
- }
- public void put(char ch) { //必须实现接口的方法
- if(putid == q.length) {
- System.out.println("The Queue is full:");
- }
- q[putid++] = ch;
- }
- public char get() { //必须实现接口的方法
- if(getid == putid) {
- System.out.println("The Queue is empty:");
- return (char) 0;
- }
- return q[getid++];
- }
- }
- public class IQDemo {
- public static void main(String[] args) {
- FixedQueue fq = new FixedQueue(10); //FixedQueue 对象
- ICharQueue iq; //接口变量
- int i;
- char ch;
- System.out.println("this is fq:");
- iq = fq; //接口变量引用对象,(接口变量可以引用任何实现接口的对象)
- for(i=0;i < 10;i++) {
- iq.put((char) ('A'+i)); //调用方法
- }
- for(i=0;i <10;i++) {
- ch = iq.get(); //调用方法
- System.out.print(ch +" ");
- }
- System.out.println();
- }
- }
- -----------------------------------------------------------------------------------
- 接口中的常量
- public interface IConst { //接口
- int MIN = 0; //接口中的常量
- int MAX = 10;
- String ERRORMSG = "error is boundary error";
- }
- class ConstDemo implements IConst { //继承接口
- public static void main(String[] args) {
- int i;
- int[] nums = new int[MAX]; //使用接口常量
- for(i=MIN;i <= 11;i++) {
- if(i >= MAX) {
- System.out.println(ERRORMSG);
- }else {
- nums[i] = i;
- System.out.println("nums[i]"+ nums[i]);
- }
- }
- System.out.println();
- }
- }
- -------------------------------------------------------------------------------
- 接口可以被拓展
- public interface A { //接口A
- void methd1();
- void methd2();
- default int getMethd(){ //默认接口方法,使用default关键字修饰
- return 1;
- }
- static int getMethd1(){ //接口中使用静态方法
- return 0;
- }
- }
- public interface B extends A{ //接口B继承接口A,拓展了接口A
- void methd3();
- }