Java method rewrite _ power node of Java College collation

  • 2020-06-23 00:27:36
  • OfStack

1. Method rewriting (Override)

How to define the rewriting in Java: Java program class inheritance features can produce a subclass, the subclass inherits the parent class had not the private property of the parent (method and variable), in subclasses can add their own properties (method and variable), at the same time also can be extended in the parent class method, to strengthen the function of their own, so call it rewritten, also known as copy or cover. Method overriding is when a method in a subclass has exactly the same method name, return value type, number of arguments to a method, and parameter type as a method inherited from the parent class.

Code:


//  This is the definition of a parent class 
public class Person {
  public void eat() {
     System.out.println("===== This is the parent class Person the eat methods =======");
   }
}
//  This is the definition of a subclass 
public class Student extends Person {
  @Override
  public void eat() {
    System.out.println("=== This is a subclass Student the eat methods ===");
  }
  // main Methods test 
  public static void main(String[] args) {
    Student student = new Student();
    student.eat(); // Output: === This is a subclass Student the eat methods ===
   }
}

When a subclass overrides a method of the parent class, it calls a method of the subclass when instantiating the subclass, as if the superclass method were overridden by 1. If you need to call a superclass method in a subclass, call the superclass method in the subclass method using the super keyword, in the form super. method name in the superclass (argument list).

Rewrite rules:

In order to achieve method rewriting, the following rules should be followed:

(1) The parameter list of the subclass method must be the same as the parameter list of the overridden method in the parent class (number and type of parameters), otherwise method overloading can only be implemented.

(2) The return value type of the subclass method must be the same as that of the overridden method in the parent class, otherwise method overloading can only be implemented.

(3) In Java, it is stipulated that the access permission of the subclass method cannot be less than that of the overridden method in the parent class, and must be greater than or equal to the access permission of the parent class.

(4) During overrides, if the overridden method in the parent class throws an exception, the method in the child class also throws an exception. But the exception that is thrown also has a bound of 1 > A subclass cannot throw more exceptions than its parent; it can only throw exceptions that are smaller than its parent, or none at all. For example, if a superclass method throws Exception, a subclass can only throw IOException or exceptions smaller than Exception or no exceptions.


Related articles: