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. }  

 

posted on 2017-11-09 14:18  欧耶d  阅读(981)  评论(0编辑  收藏  举报

导航