JAVA的extends用法

 理解继承是理解面向对象程序设计的关键。在Java中,通过关键字extends继承一个已有的类,被继承的类称为父类(超类,基类),新的类称为子类(派生类)。在Java中不允许多继承。
(1)继承

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. class Animal{  
  2.     void eat(){  
  3.         System.out.println("Animal eat");  
  4.     }  
  5.     void sleep(){  
  6.         System.out.println("Animal sleep");  
  7.     }  
  8.     void breathe(){  
  9.         System.out.println("Animal breathe");  
  10.     }  
  11. }  
  12.   
  13. class Fish extends Animal{  
  14. }  
  15.   
  16. public class TestNew {  
  17.     public static void main(String[] args) {  
  18.         // TODO Auto-generated method stub  
  19.         Animal an = new Animal();  
  20.         Fish fn = new Fish();  
  21.           
  22.         an.breathe();  
  23.         fn.breathe();  
  24.     }  
  25. }  

在eclipse执行得:
Animal breathe! 
Animal breathe! 
.java文件中的每个类都会在文件夹bin下生成一个对应的.class文件。执行结果说明派生类继承了父类的所有方法。

(2)覆盖

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. class Animal{  
  2.     void eat(){  
  3.         System.out.println("Animal eat");  
  4.     }  
  5.     void sleep(){  
  6.         System.out.println("Animal sleep");  
  7.     }  
  8.     void breathe(){  
  9.         System.out.println("Animal breathe");  
  10.     }  
  11. }  
  12.   
  13. class Fish extends Animal{  
  14.     void breathe(){  
  15.         System.out.println("Fish breathe");  
  16.     }  
  17. }  
  18.   
  19. public class TestNew {  
  20.     public static void main(String[] args) {  
  21.         // TODO Auto-generated method stub  
  22.         Animal an = new Animal();  
  23.         Fish fn = new Fish();  
  24.           
  25.         an.breathe();  
  26.         fn.breathe();  
  27.     }  
  28. }  

执行结果:

Animal breathe
Fish breathe

在子类中定义一个与父类同名,返回类型,参数类型均相同的一个方法,称为方法的覆盖。方法的覆盖发生在子类与父类之间。另外,可用super提供对父类的访问。

 

参考原文:http://blog.csdn.net/zhandoushi1982/article/details/5441126

posted @ 2014-12-23 19:46  Sugata  阅读(570)  评论(0编辑  收藏  举报