Java 简明教程

Java - Overriding

在上一章中,我们讨论了超类和子类。如果一个类从其超类继承了一个方法,那么就有机会覆盖该方法,前提是它没有被标记为 final。

In the previous chapter, we talked about superclasses and subclasses. If a class inherits a method from its superclass, then there is a chance to override the method provided that it is not marked final.

Benefit of Overriding in Java

重写的优点是:能够定义特定于子类类型的一种行为,这意味着子类可以根据其需求实现父类方法。

The benefit of overriding is: ability to define a behavior that’s specific to the subclass type, which means a subclass can implement a parent class method based on its requirement.

object-oriented 术语中,重写是指重写现有 method 的功能。

In object-oriented terms, overriding means to override the functionality of an existing method.

Java Method Overriding

Method overriding 使我们能够实现运行时 polymorphism ,用于编写超类中已定义的子类方法的特定定义。

Method overriding allows us to achieve run-time polymorphism and is used for writing specific definitions of a subclass method that is already defined in the superclass.

超类方法和在子类中覆盖的方法应该具有相同的声明签名,例如参数列表、类型和返回类型。

The method is superclass and overridden method in the subclass should have the same declaration signature such as parameters list, type, and return type.

Usage of Java Method Overriding

以下是方法覆盖在 Java 中的两种重要用法:

Following are the two important usages of method overriding in Java:

  1. Method overriding is used for achieving run-time polymorphism.

  2. Method overriding is used for writing specific definition of a subclass method (this method is known as the overridden method).

Example of Method Overriding in Java

我们来看一个示例。

Let us look at an example.

class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}

class Dog extends Animal {
   public void move() {
      System.out.println("Dogs can walk and run");
   }
}

public class TestDog {

   public static void main(String args[]) {
      Animal a = new Animal();   // Animal reference and object
      Animal b = new Dog();   // Animal reference but Dog object

      a.move();   // runs the method in Animal class
      b.move();   // runs the method in Dog class
   }
}
Animals can move
Dogs can walk and run

在上面的示例中,尽管 b 是 Animal 的一种类型,但它运行 Dog 类中的 move 方法。这样做的原因是:在编译时,针对引用类型进行检查。然而,在运行时,JVM 找出对象类型,并运行属于该特定对象的该方法。

In the above example, you can see that even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object.

因此,在上面的示例中,程序将正确编译,因为 Animal 类具有 move 方法。然后,在运行时,运行特定于该对象的方法。

Therefore, in the above example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object.

考虑以下示例 −

Consider the following example −

Example

class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}

class Dog extends Animal {
   public void move() {
      System.out.println("Dogs can walk and run");
   }
   public void bark() {
      System.out.println("Dogs can bark");
   }
}

public class TestDog {

   public static void main(String args[]) {
      Animal a = new Animal();   // Animal reference and object
      Animal b = new Dog();   // Animal reference but Dog object

      a.move();   // runs the method in Animal class
      b.move();   // runs the method in Dog class
      b.bark();
   }
}
TestDog.java:26: error: cannot find symbol
      b.bark();
       ^
  symbol:   method bark()
  location: variable b of type Animal
1 error

此程序将抛出编译时错误,因为 b 的引用类型 Animal 没有任何名为 bark 的方法。

This program will throw a compile time error since b’s reference type Animal doesn’t have a method by the name of bark.

Rules for Method Overriding

  1. The argument list should be exactly the same as that of the overridden method.

  2. The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass.

  3. The access level cannot be more restrictive than the overridden method’s access level. For example: If the superclass method is declared public then the overridding method in the sub class cannot be either private or protected.

  4. Instance methods can be overridden only if they are inherited by the subclass.

  5. A method declared final cannot be overridden.

  6. A method declared static cannot be overridden but can be re-declared.

  7. If a method cannot be inherited, then it cannot be overridden.

  8. A subclass within the same package as the instance’s superclass can override any superclass method that is not declared private or final.

  9. A subclass in a different package can only override the non-final methods declared public or protected.

  10. An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.

  11. Constructors cannot be overridden.

Java Method and Constructor Overriding

在 Java 中,每个类都有不同的名称,且构造函数的名称与类名称相同。因此,我们无法重写 constructor ,因为它们不能具有相同的名称。

In Java, each class has a different name and the constructor’s name is the same as the class name. Thus, we cannot override a constructor as they cannot have the same name.

Java Method Overriding: Using the super Keyword

当调用一个被覆盖方法的超类版本时,使用 super 关键字。

When invoking a superclass version of an overridden method the super keyword is used.

Example: Using the super Keyword

class Animal {
   public void move() {
      System.out.println("Animals can move");
   }
}

class Dog extends Animal {
   public void move() {
      super.move();   // invokes the super class method
      System.out.println("Dogs can walk and run");
   }
}

public class TestDog {

   public static void main(String args[]) {
      Animal b = new Dog();   // Animal reference but Dog object
      b.move();   // runs the method in Dog class
   }
}
Animals can move
Dogs can walk and run