JAVA的extends用法

时间:2022-06-03 17:47:50

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

  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. class Fish extends Animal{
  13. }
  14. public class TestNew {
  15. public static void main(String[] args) {
  16. // TODO Auto-generated method stub
  17. Animal an = new Animal();
  18. Fish fn = new Fish();
  19. an.breathe();
  20. fn.breathe();
  21. }
  22. }

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

(2)覆盖

  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. class Fish extends Animal{
  13. void breathe(){
  14. System.out.println("Fish breathe");
  15. }
  16. }
  17. public class TestNew {
  18. public static void main(String[] args) {
  19. // TODO Auto-generated method stub
  20. Animal an = new Animal();
  21. Fish fn = new Fish();
  22. an.breathe();
  23. fn.breathe();
  24. }
  25. }

执行结果:

Animal breathe
Fish breathe

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

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