The difference between Java override and overload

Table of contents

Override

Method rewriting rules

 Use of Super keyword

Overload

Difference Between Overriding and Overloading

Summarize


Override

Rewriting is the process of rewriting the implementation of methods of the parent class that are allowed to be accessed by the subclass. Neither the return value nor the formal parameters can be changed. That is, the shell remains unchanged and the core is rewritten!

The advantage of overriding is that subclasses can define their own behavior as needed. In other words, subclasses can implement the methods of the parent class as needed.

Overriding methods cannot throw new checked exceptions or exceptions that are broader than those declared by the overridden method. For example: A method of the parent class declares a checked exception IOException, but when overriding this method, it cannot throw an Exception because Exception is the parent class of IOException and throws an IOException exception or a subclass exception of IOException.

In object-oriented principles, overriding means that any existing method can be overridden. Examples are as follows:

TestDog.java file code:

class Animal{
   public void move(){
      System.out.println("动物可以移动");
   }
}
 
class Dog extends Animal{
   public void move(){
      System.out.println("狗可以跑和走");
   }
}
 
public class TestDog{
   public static void main(String args[]){
      Animal a = new Animal(); // Animal 对象
      Animal b = new Dog(); // Dog 对象
 
      a.move();// 执行 Animal 类的方法
 
      b.move();//执行 Dog 类的方法
   }
}

 The compilation and running results of the above example are as follows:

动物可以移动
狗可以跑和走

As you can see in the above example, although b belongs to the Animal type, it runs the move method of the Dog class.

This is because during the compilation phase, only the reference type of the parameter is checked.

However, at runtime, the Java Virtual Machine (JVM) specifies the type of object and runs the object's methods.

Therefore, in the above example, the compilation is successful because the move method exists in the Animal class. However, at runtime, the method of the specific object is run.

Consider the following examples:

TestDog.java file code:

class Animal{
   public void move(){
      System.out.println("动物可以移动");
   }
}
 
class Dog extends Animal{
   public void move(){
      System.out.println("狗可以跑和走");
   }
   public void bark(){
      System.out.println("狗可以吠叫");
   }
}
 
public class TestDog{
   public static void main(String args[]){
      Animal a = new Animal(); // Animal 对象
      Animal b = new Dog(); // Dog 对象
 
      a.move();// 执行 Animal 类的方法
      b.move();//执行 Dog 类的方法
      b.bark();
   }
}

The compilation and running results of the above example are as follows:

TestDog.java:30: cannot find symbol
symbol  : method bark()
location: class Animal
                b.bark();
                 ^

The program will throw a compilation error because b's reference type Animal does not have a bark method.

Method rewriting rules

  • The parameter list must be exactly the same as the parameter list of the overridden method.

  • The return type can be different from the return type of the overridden method, but it must be a derived class of the parent class's return value (the return type must be the same in Java5 and earlier versions, but can be different in Java7 and later versions).

  • Access permissions cannot be lower than the access permissions of overridden methods in the parent class. For example: If a method of the parent class is declared as public, then the method cannot be declared as protected when overriding it in the subclass.

  • Member methods of a parent class can only be overridden by its subclasses.

  • Methods declared final cannot be overridden.

  • Methods declared static cannot be overridden, but can be declared again.

  • If the subclass and the parent class are in the same package, the subclass can override all methods of the parent class, except methods declared as private and final.

  • If the subclass and the parent class are not in the same package, the subclass can only override the non-final methods of the parent class that are declared public and protected.

  • An overridden method can throw any unforced exception, regardless of whether the overridden method throws an exception. However, an overridden method cannot throw new mandatory exceptions, or mandatory exceptions that are broader than those declared by the overridden method, and vice versa.

  • Constructors cannot be overridden.

  • If you cannot inherit from a class, you cannot override the methods of that class.

Use of Super keyword

When you need to call an overridden method of the parent class in a subclass, use the super keyword.

 TestDog.java file code:

class Animal{
   public void move(){
      System.out.println("动物可以移动");
   }
}
 
class Dog extends Animal{
   public void move(){
      super.move(); // 应用super类的方法
      System.out.println("狗可以跑和走");
   }
}
 
public class TestDog{
   public static void main(String args[]){
 
      Animal b = new Dog(); // Dog 对象
      b.move(); //执行 Dog类的方法
 
   }
}

 The compilation and running results of the above example are as follows:

动物可以移动
狗可以跑和走

Overload

Overloading is a method with the same name but different parameters in a class. The return types can be the same or different.

Each overloaded method (or constructor) must have a unique list of parameter types.

The most commonly used place is the overloading of the constructor.

Overloading rules:

  • The overloaded method must change the parameter list (the number or types of parameters are different);
  • Overloaded methods can change the return type;
  • Overloaded methods can change access modifiers;
  • Overloaded methods can declare new or wider checked exceptions;
  • Methods can be overloaded in the same class or in a subclass.
  • The return value type cannot be used as a criterion for distinguishing overloaded functions.

 Example

 Overloading.java file code:

public class Overloading {
    public int test(){
        System.out.println("test1");
        return 1;
    }
 
    public void test(int a){
        System.out.println("test2");
    }   
 
    //以下两个参数类型顺序不同
    public String test(int a,String s){
        System.out.println("test3");
        return "returntest3";
    }   
 
    public String test(String s,int a){
        System.out.println("test4");
        return "returntest4";
    }   
 
    public static void main(String[] args){
        Overloading o = new Overloading();
        System.out.println(o.test());
        o.test(1);
        System.out.println(o.test(1,"test3"));
        System.out.println(o.test("test4",1));
    }
}

Difference Between Overriding and Overloading

Difference Overloaded methods overridden method
parameter list Must be modified Must not be modified
Return type Can be modified Must not be modified
abnormal Can be modified It can be reduced or deleted, but new or wider exceptions must not be thrown.
access Can be modified Must not make stricter restrictions (restrictions can be lowered)

Summarize

Overriding and overloading of methods are different manifestations of polymorphism in Java. Overriding is a manifestation of polymorphism between parent classes and subclasses. Overloading can be understood as a specific manifestation of polymorphism. form.

  • (1) Method overloading is when multiple methods with the same name are defined in a class, but the number of their parameters is different or the number is the same but the type and order are different, it is called method overloading.
  • (2) Method overriding is a method in which a method in a subclass has the same name as the method in the parent class, has the same number and type of parameters, and the same return value, which is called overriding.
  • (3) Method overloading is a polymorphic manifestation of a class, while method overriding is a polymorphic manifestation of a subclass and a parent class.

 

Guess you like

Origin blog.csdn.net/qq_61902168/article/details/129133784