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. }  
  • 相关阅读:
    【C#】C#获取文件夹下的所有文件
    6 云计算系列之Nova安装与配置
    5 云计算系列之glance镜像服务安装
    4 云计算系列之Openstack简介与keystone安装
    3大数据挖掘系列之文本相似度匹配
    6 Django系列之关于models的sql语句日常用法总结
    2 python大数据挖掘系列之淘宝商城数据预处理实战
    5 Django系列之通过list_display展示多对多与外键内容在admin-web界面下
    1 python大数据挖掘系列之基础知识入门
    4 django系列之HTML通过form标签来同时提交表单内容与上传文件
  • 原文地址:https://www.cnblogs.com/o-ye/p/7809136.html
Copyright © 2011-2022 走看看