Chinaunix首页 | 论坛 | 博客
  • 博客访问: 927888
  • 博文数量: 210
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2070
  • 用 户 组: 普通用户
  • 注册时间: 2014-11-19 21:54
文章分类

全部博文(210)

文章存档

2020年(2)

2019年(18)

2018年(27)

2017年(5)

2016年(53)

2015年(88)

2014年(17)

分类: Java

2015-12-19 15:02:02

     理解继承是理解面向对象程序设计的关键。在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提供对父类的访问。

阅读(1575) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~