刚刚初步学习了java的接口,在这里将自己的收获写下来:
package com.funyoo.about_interface; public interface MyFirstInterface { public static final int red = 1; int blue = 2; public abstract void func(); int fun(); }
定义第一个接口:MyFirstInterface
注意:接口存在以下”铁律“:接口对其成员会用 public static final联合修饰;
对其方法会用public abstract联合修饰
所以,上面的成员blue也被public, static, final 联合修饰,方法fun()也被public, abstract 联合修饰。
package com.funyoo.about_interface; public interface MySecondInterface extends MyFirstInterface { public static final int red = 2; public int fun2(); }
这是定义的第二个接口,MySecondInterface,使其继承了第一个接口MyfirstInterface;
package com.funyoo.about_interface; public interface MyThirdInterface extends MyFirstInterface { int red = 3; }
定义第三个接口,MyThirdInterface,同样其继承了第一个接口MyfirstInterface;
现在我们新建一个类来实现第一个接口:ImplemensMyfirstInterface
package com.funyoo.about_interface; public class ImplemensMyfirstInterface implements MyFirstInterface { @Override public void func() { } @Override public int fun() { return 0; } }
因为接口所创建的方法均为抽象方法,所以在被实现的时候,其抽象方法也应实现。
接下来我们在新建一个类来实现所有的接口:ImplemensMyInterface
package com.funyoo.about_interface; public class ImplemensMyInterface implements MyFirstInterface, MySecondInterface, MyThirdInterface { @Override public int fun2() { return MyFirstInterface.red; } @Override public void func() { // TODO 自动生成的方法存根 } @Override public int fun() { return MyFirstInterface.red; } }
下面我们建立一个主类来进行一项实验:
package com.funyoo.about_interface.test; import com.funyoo.about_interface.ImplemensMyInterface; import com.funyoo.about_interface.ImplemensMyfirstInterface; import com.funyoo.about_interface.MyFirstInterface; import com.funyoo.about_interface.MySecondInterface; import com.funyoo.about_interface.MyThirdInterface; public class Test { public static void main(String[] args) { ImplemensMyInterface imi = new ImplemensMyInterface(); ImplemensMyfirstInterface imf = new ImplemensMyfirstInterface(); // 等同于 // MyFirstInterface imi = new ImplemensMyInterface(); // MyFirstInterface imf = new ImplemensMyfirstInterface(); System.out.println(imi instanceof MyFirstInterface); //true //*** System.out.println(imi instanceof MySecondInterface); //true System.out.println(imi instanceof MyThirdInterface); //true System.out.println(imi instanceof ImplemensMyInterface); //true System.out.println("--------------------------------"); System.out.println(imf instanceof MyFirstInterface); //true //*** System.out.println(imf instanceof MySecondInterface); //false System.out.println(imf instanceof MyThirdInterface); //false System.out.println("---------------------------------"); System.out.println(imi.getClass()); //class com.funyoo.about_interface.ImplemensMyInterface System.out.println(imf.getClass()); //class com.funyoo.about_interface.ImplemensMyfirstInterface } }
通过上面的程序和运行的结果来看,imi和imf属于两个不同的类,却因为一个接口而被联系起来;
再看19行和26行的运行结果
我们可以大胆的把12,13行的ImplemensMyInterface和ImplemensMyfirstInterface都改为:
MyFirstInterface
程序运行结果不变!
所以以后的编程中我们完全可以把两个完全不同的类用一个接口进行“链接”起来!