小白教程

 找回密码
 立即注册
小白教程 首页 系列教程 Java系列教程 查看内容

Java 重写 (Override)

发布者: 小白教程

重写 (Override)

重写是子类对父类的允许访问的方法的实现过程进行重新编写!返回值和形参都不能改变。即外壳不变,核心重写!

重写的好处在于子类可以根据需要,定义特定于自己的行为。

也就是说子类能够根据需要实现父类的方法。

在面向对象原则里,重写意味着可以重写任何现有方法。实例如下:

  1. class Animal{
  2. public void move(){
  3. System.out.println("动物可以移动");
  4. }
  5. }
  6. class Dog extends Animal{
  7. public void move(){
  8. System.out.println("狗可以跑和走");
  9. }
  10. }
  11. public class TestDog{
  12. public static void main(String args[]){
  13. Animal a = new Animal(); // Animal 对象
  14. Animal b = new Dog(); // Dog 对象
  15. a.move();// 执行 Animal 类的方法
  16. b.move();//执行 Dog 类的方法
  17. }
  18. }

以上实例编译运行结果如下:

  1. 动物可以移动
  2. 狗可以跑和走

在上面的例子中可以看到,尽管 b 属于 Animal 类型,但是它运行的是 Dog 类的 move 方法。

这是由于在编译阶段,只是检查参数的引用类型。

然而在运行时,Java 虚拟机 (JVM) 指定对象的类型并且运行该对象的方法。

因此在上面的例子中,之所以能编译成功,是因为 Animal 类中存在 move 方法,然而运行时,运行的是特定对象的方法。

思考以下例子:

  1. class Animal{
  2. public void move(){
  3. System.out.println("动物可以移动");
  4. }
  5. }
  6. class Dog extends Animal{
  7. public void move(){
  8. System.out.println("狗可以跑和走");
  9. }
  10. public void bark(){
  11. System.out.println("狗可以吠叫");
  12. }
  13. }
  14. public class TestDog{
  15. public static void main(String args[]){
  16. Animal a = new Animal(); // Animal 对象
  17. Animal b = new Dog(); // Dog 对象
  18. a.move();// 执行 Animal 类的方法
  19. b.move();//执行 Dog 类的方法
  20. a.bark();//执行 Animal 类的方法
  21. }
  22. }

以上实例编译运行结果如下:

  1. TestDog.java:30: cannot find symbol
  2. symbol : method bark()
  3. location: class Animal
  4. a.bark();
  5. ^

该程序将抛出一个编译错误,因为 a 的引用类型 Animal 没有 bark 方法。


方法重写的规则

  • 参数列表与被重写方法的参数列表必须完全相同。
  • 返回类型与被重写方法的返回类型可以不相同,但是必须是父类返回值的派生类(java5 及更早版本返回类型要一样,java7 及更高版本可以不同)。
  • 子类方法的访问权限必须大于或等于父类方法的访问权限。例如:如果父类的一个方法被声明为 public,那么在子类中重写该方法就不能声明为 protected。
  • 父类的成员方法只能被它的子类重写。
  • 声明为 final 的方法不能被重写。
  • 声明为 static 的方法不能被重写,但是能够被再次声明。
  • 子类和父类在同一个包中,那么子类可以重写父类所有方法,除了声明为 private 和 final 的方法。
  • 子类和父类不在同一个包中,那么子类只能够重写父类的声明为 public 和 protected 的非 final 方法。
  • 重写的方法能够抛出任何非强制异常,无论被重写的方法是否抛出异常。但是,重写的方法不能抛出新的强制性异常,或者比被重写方法声明的更广泛的强制性异常,反之则可以。
  • 构造方法不能被重写。
  • 如果不能继承一个方法,则不能重写这个方法。
  • 访问权限不能比父类中被重写的方法的访问权限更低。例如:如果父类的一个方法被声明为 public,那么在子类中重写该方法就不能声明为 protected。

Super 关键字的使用

当需要在子类中调用父类的被重写方法时,要使用 super 关键字。

  1. class Animal{
  2. public void move(){
  3. System.out.println("动物可以移动");
  4. }
  5. }
  6. class Dog extends Animal{
  7. public void move(){
  8. super.move(); // 应用super类的方法
  9. System.out.println("狗可以跑和走");
  10. }
  11. }
  12. public class TestDog{
  13. public static void main(String args[]){
  14. Animal b = new Dog(); //
  15. b.move(); //执行 Dog类的方法
  16. }
  17. }

以上实例编译运行结果如下:

  1. 动物可以移动
  2. 狗可以跑和走


上一篇:Java 继承下一篇:重载 (Overload)

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 06:22 , Processed in 0.022053 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部