zoukankan      html  css  js  c++  java
  • Java 中extends与implements使用方法

    extends与implements的区别:

    extends 是继承父类,只要那个类不是声明为final或者那个类定义为abstract的就能继承,JAVA中不支持多重继承,但是可以用接口来实现,这样就用到了implements,继承只能继承一个类,但implements可以实现多个接口,用逗号分开就行了。

    比如: 

    class A extends B implements C,D,E {}    (class 子类名 extends 父类名 implenments 接口名)

    [c-sharp] view plain copy
     
    1. //定义一个Runner接口   
    2. public inerface Runner   
    3. {  
    4.    int ID = 1;  
    5.    void run ();  
    6. }   
    [java] view plain copy
     
    1. //定义一个interface Animal,它继承于父类Runner  
    2. interface Animal extends Runner  
    3. {  
    4.    void breathe ();  
    5. }  
    [c-sharp] view plain copy
     
    1. //定义Fish类,它实现了Animal接口的方法run()和breather()  
    2. class Fish implements Animal  
    3. {  
    4.    public void run ()    //实现了Animal方法run()  
    5.  {  
    6.     System.out.println("fish is swimming");  
    7.  }  
    8. public void breather()  
    9.  {  
    10.     System.out.println("fish is bubbing");     
    11.  }  
    12. }  
    13. //定义了一个抽象类LandAnimal,它实现了接口Animal的方法。  
    14. abstract LandAnimal implements Animal  
    15. {  
    16.     
    17.    public void breather ()  
    18.  {  
    19.     System.out.println("LandAnimal is breathing");  
    20.  }  
    21. }  
    22. //定义了一个类Student,它继承了类Person,并实现了Runner接口的方法run()。  
    23. class Student extends Person implements Runner  
    24. {  
    25.     ......  
    26.     public void run ()  
    27.      {  
    28.           System.out.println("the student is running");  
    29.      }  
    30.     ......  
    31. }  
    32.    
    33. //定义了一个接口Flyer  
    34. interface Flyer  
    35. {  
    36.    void fly ();  
    37. }  
    38.    
    39. //定义了一个类Bird,它实现了Runner和Flyer这两个接口定义的方法。  
    40. class Bird implements Runner , Flyer  
    41. {  
    42.    public void run ()   //Runner接口定义的方法。  
    43.     {  
    44.         System.out.println("the bird is running");  
    45.     }  
    46.    public void fly ()   //Flyer接口定义的方法。  
    47.     {  
    48.         System.out.println("the bird is flying");  
    49.     }  
    50. }  
    51.    
    52. //TestFish类  
    53. class TestFish  
    54. {  
    55.    public static void main (String args[])  
    56.     {  
    57.        Fish f = new Fish();  
    58.        int j = 0;  
    59.        j = Runner.ID;  
    60.        j = f.ID;  
    61.     }  
    62. }  
  • 相关阅读:
    软件构造 第七章第三节 断言和防御性编程
    软件构造 第七章第二节 错误与异常处理
    软件构造 第七章第一节 健壮性和正确性的区别
    软件构造 第六章第三节 面向可维护的构造技术
    软件构造 第六章第二节 可维护的设计模式
    欧拉函数代码实现及扩展--快速矩阵幂
    编译原理
    算法设计与分析总结
    人工智能简答总结
    感想
  • 原文地址:https://www.cnblogs.com/o-ye/p/7809136.html
Copyright © 2011-2022 走看看