zoukankan      html  css  js  c++  java
  • Java:接口继承接口 (多继承机制)

    在看API文档时,突然发现一个接口可以是其他接口的子接口,这说明接口之间会存在继承的关系。查找了相关的资料,做一个总结。

    是继承还是实现

    首先要搞清楚接口之间的关系使用的关键字是extends还是implement。网友有如下回答:

    一个类只能extends一个父类,但可以implements多个接口。java通过使用接口的概念来取代C++中多继承。与此同时,一个接口则可以同时extends多个接口,却不能implements任何接口。因而,Java中的接口是支持多继承的。

    自己动手验证了一下:

    首先在eclipse中创建interface时,弹出选项窗口中会有一个选项:

    可以看到eclipse中也明确提示可以使用extends关键字继承上层接口

    再看测试代码清单:

    Interface1:

    1. public interface Interface1 {  
    2.       
    3.     public void method1();  
    4. }  

    Interface2:


    看到接口之间的关系使用implements关键字时会报错,错误提示信息如下:

    1. Syntax error on token "implements", extends expected  

    eclipse明确指出,接口之间是继承关系,而非实现关系。

    修改为extends时代码正确:

    1. public interface Interface2 extends Interface1{  
    2.     public int a = 1;  
    3.     public void method2();  
    4. }  

     

    前面网友又提到java接口是可以支持多继承的。做了一下实验:

    代码清单:

    1. //interface3  
    2. <pre name="code" class="java">public interface Interface3 {  
    3.     public void method3();  
    4. }  

    //interface4

    1. <pre name="code" class="java">public interface Interface4 extends Interface1, Interface3 {  
    2.     public void method4();  
    3. }  

    实现类A:

    1. public class A implements Interface4 {  
    2.   
    3.     public static void main(String[] args) {  
    4.           
    5.     }  
    6.     @Override  
    7.     public void method1() {  
    8.         // TODO Auto-generated method stub  
    9.         System.out.println("method1");  
    10.     }  
    11.   
    12.     @Override  
    13.     public void method3() {  
    14.         // TODO Auto-generated method stub  
    15.         System.out.println("method2");  
    16.     }  
    17.   
    18.     @Override  
    19.     public void method4() {  
    20.         // TODO Auto-generated method stub  
    21.         System.out.println("method3");  
    22.     }  
    23.       
    24.       
    25. }  

    Main主类:

    1. public class Main {  
    2.   
    3.     public static void main(String[] args) {  
    4.         // TODO Auto-generated method stub  
    5.         A a = new A();  
    6.         a.method1();  
    7.         a.method3();  
    8.         a.method4();  
    9.     }  
    10.   
    11. }  

    输出结果:

    1. method1  
    2. method2  
    3. method3  

    说明java接口的继承是多继承的机制。

  • 相关阅读:
    准备开始学习XNA
    徐家骏:华为十年感悟
    memcached详解
    sql时间
    Sql server log file 缩小和删除
    看高手都是运用的灵活自如,打算从今天开始学习他!
    什么是内存对齐
    VS 2008 远程调试 与asp.net
    XNA入门的代码注释
    HTML的段落与文字
  • 原文地址:https://www.cnblogs.com/dengyungao/p/7524960.html
Copyright © 2011-2022 走看看