Java中在接口的应用中,要注意一下几点:
<1>接口一般定义的是常量和一些抽象方法。抽象类中可以包含抽象方法,也可以有非抽象方法,但是有抽象方法的类一定是抽象类。抽象方法不能有方法体。
<2>在引用接口时,接口的引用指向实现的对象,尽量定义为接口或父类的引用。这其中有可能用到多态的知识。引用接口用implements。
<3>接口(interface)只能定义抽象方法而且默认为是Public。常量是public static final 修饰的
<4>通过implements来引用接口。例:Class runnrtmp inplements runner.
<5>多个无关类可以实现一个接口,!!!!接口的引用指向实现的对象。
<6>一个类可以实现多个无关的接口(这点和继承要有所区别)
<7>和继承一样,接口与实现类之间存在多态性。
<8>接口可以继承其他的接口,并添加新的属性和抽象方法。
<9>在类中实现接口的方法时必须加上public修饰符
下面通过一个例子来对上面的要点进行下说明
接口的应用1:
- interface Runner //定义接口
- {
- int i=3;
- public void start();
- void run();
- void stop();
- }
- interface Eater extends Runner //接口间可以继承
- {
- public final static int j=4;
- void openMouth();
- void upAndDown();
- void goIn();
- }
- class TT implements Eater //引用接口
- {
- public void start()
- {
- System.out.println("---------start()-------");
- }
- public void run()
- {
- System.out.println("---------run()-------");
- }
- public void stop()
- {
- System.out.println("---------stop()-------");
- }
- public void openMouth()
- {
- System.out.println("---------openMouth()-------");
- }
- public void upAndDown()
- {
- System.out.println("---------upAndDown()-------");
- }
- public void goIn()
- {
- System.out.println("---------goIn()-------");
- }
- }
- public class TestInterface
- {
- public static void main(String[] args)
- {
- Runner tt=new TT();//接口的引用指向实现的对象
- System.out.println(tt.i);
- System.out.println(Runner.i);
- tt.start();
- Eater ee=new TT();
- System.out.println(ee.j);
- System.out.println(Eater.j);
- ee.start();
- }
- }
接口的应用2:
1 public class TestInterface { 2 3 public static void main(String[] args){ 4 5 CareAnimalable c = new Worker(); 6 //Worker w = (Worker)c; 7 TestInterface t = new TestInterface(); 8 t.t(c); //多态 9 10 c = new Farmer(); 11 t.t(c); 12 13 14 } 15 16 public void t(CareAnimalable c){//尽量定义为接口或父类的引用 17 c.feed(); 18 c.play(); 19 } 20 } 21 22 23 interface CareAnimalable{ 24 public void feed(); 25 public void play(); 26 } 27 28 class Worker implements CareAnimalable{ 29 30 public void feed(){ 31 System.out.println("-----feed()----"); 32 } 33 34 public void play(){ 35 System.out.println("-----play()----"); 36 } 37 } 38 39 class Farmer implements CareAnimalable{ 40 41 public void feed(){ 42 System.out.println("-----Farmer feed()----"); 43 } 44 45 public void play(){ 46 System.out.println("-----Farmer play()----"); 47 } 48 }
以上就是接口的用法,在编程开发中我们可以通过定义接口来简便编程。在ANDROID开发中,接口的用处很大,所以希望大家能把接口的知识掌握。