The difference between java rewriting and overloading

In Java, override and overload are two different concepts:

  1. Override:
    • Overriding means that a subclass redefines (overrides) a method inherited from a parent class.
    • Overriding requires that the subclass method has the same method name, parameter list, and return type as the parent class method.
    • Overriding can modify or extend the functionality of a parent class method, but it cannot change the signature of the method.
    • Overriding can take advantage of polymorphism and call the corresponding method at runtime based on the actual type of the object.

Sample code:

class Animal {
    
    
    public void makeSound() {
    
    
        System.out.println("Animal makes sound");
    }
}

class Dog extends Animal {
    
    
    @Override
    public void makeSound() {
    
    
        System.out.println("Dog barks");
    }
}

Animal animal = new Dog();
animal.makeSound(); // 输出:"Dog barks"
  1. Overload:
    • Overloading means that in the same class, multiple methods with the same name but different parameter lists can be defined.
    • The characteristic of overloaded methods is that the number, type or order of parameters are different.
    • The compiler decides which overloaded method to call based on the method's parameter list.
    • Overloading can provide a more flexible way of calling methods, making it easier to handle different logical operations in different situations.

Sample code:

class Calculator {
    
    
    public int add(int a, int b) {
    
    
        return a + b;
    }

    public double add(double a, double b) {
    
    
        return a + b;
    }
}

Calculator calculator = new Calculator();
int result1 = calculator.add(5, 3);          // 调用 int add(int a, int b)
double result2 = calculator.add(2.5, 4.7);   // 调用 double add(double a, double b)

Through rewriting and overloading, code flexibility and extensibility can be achieved. 重写用于在子类中修改父类方法的行为, implement specific logic; 重载用于定义多个相似功能但参数不同的方法, provide more choices.

Guess you like

Origin blog.csdn.net/drhnb/article/details/132252181