java 接口

在讨论接口之前我买必须先看一看抽象类。

1、抽象类:

 1 /**
 2  * 常规写法
 3  * 2016/5/5
 4 **/
 5 package cn.Java_7;
 6 class Fruit{
 7     public void eat(){
 8         System.out.println("eat fruit");
 9     }
10 }
11 class Apple extends Fruit{
12     public void eat(){
13         System.out.println("eat apple");
14     }
15 }
16 class Orange extends Fruit{
17     public void eat(){
18         System.out.println("eat orange");
19     }
20 }
21 class Banana extends Fruit{
22     public void eat(){
23         System.out.println("eat banana");
24     }
25 }
26 public class AllFruit {
27     public static void eatFruit(Apple apple){
28         apple.eat();
29     }
30     public static void eatFruit(Orange orange){
31         orange.eat();
32     }
33     public static void eatFruit(Banana banana){
34         banana.eat();
35     }
36     
37     public static void main(String[] args) {
38         eatFruit(new Apple());
39         eatFruit(new Orange());
40         eatFruit(new Banana());
41     }
42 
43 }

抽象类:包含抽象方法的类就叫做抽象类,如果一个类中包含多个抽象方法,该类就必须限定为抽象的(abstract),在上一章多态当中,Fruit就可 以看做一个抽象类,我们不能对Fruit创建对象,因为水果是一类东西,不能成为一种具体的东西,我们吃水果只能说吃某种具体的水果,比如吃香蕉,吃苹 果,吃橘子,不能实例化吃水果,水果这种东西时不存在的,只能用具体的方法去覆盖吃水果这样一个动作。

   如果一个方法被abstract限定为抽象的,那么包含这个方法的类也必须被限定为抽象的,如果一个类继承的一个抽象类,那么这个类就必须全部覆盖父类中所有的抽象方法,否则这个类也便认为是一个抽象类。

2、接口

abstract关键字允许人们类中创建一个没有任何定义的方法,提供了接口的部分,但是没有提供相应的具体的实现。

interface关键字产生一个完全抽象的类,它根本就没有提供任何具体的实现,它允许创建者确定方法名、参数列表,和返回类型,但是没有方法体。

 1 /**
 2  * 接口
 3  * 2016/5/5
 4  **/
 5 package cn.Java_7;
 6 interface Fruit{
 7     void eat(int a);
 8 }
 9 class Apple implements Fruit{
10     public void eat(int a){
11         System.out.println("小明吃了"+a+"个苹果");
12     }
13 }
14 class Orang implements Fruit{
15     public void eat(int a ){
16         System.out.println("小芳吃了"+a+"个橘子");
17     }
18 }
19 class Banana implements Fruit{
20     public void eat (int a){
21         System.out.println("小王吃了"+a+"个香蕉");
22     }
23 }
24 public class AllFruit {
25     public static void main(String[] args) {
26         Fruit apple = new Apple();
27         Fruit orange = new Orang();
28         Fruit banana = new Banana();
29         apple.eat(4);
30         orange.eat(5);
31         banana.eat(6);
32 
33     }
34 
35 }

 3、多重继承

 一个类只能继承一个类,而接口可以实现多继承

1     public class A extends B implements C,D,E{}  

4、接口中的域

放在接口中的任何域都自动是static和final的,同时也是public的。

原文地址:https://www.cnblogs.com/snail-lb/p/5463268.html