Java 中的覆寫與過載

介紹

覆寫重載是Java編程的核心概念。它們是在Java程序中實現多態性的方法。多態性是面向對象編程的概念之一。OOPS概念之一。

Screenshot of Java code with arrows pointing at instances where overloading and overriding are occurring.

當超類和子類中的方法簽名(名稱和參數)相同時,稱為覆寫。當同一類中的兩個或多個方法具有相同的名稱但參數不同時,稱為重載

比較覆寫和重載

Overriding Overloading
Implements “runtime polymorphism” Implements “compile time polymorphism”
The method call is determined at runtime based on the object type The method call is determined at compile time
Occurs between superclass and subclass Occurs between the methods in the same class
Have the same signature (name and method arguments) Have the same name, but the parameters are different
On error, the effect will be visible at runtime On error, it can be caught at compile time

覆寫和重載示例

這是Java程序中覆寫和重載的示例:

package com.journaldev.examples;

import java.util.Arrays;

public class Processor {

	public void process(int i, int j) {
		System.out.printf("Processing two integers:%d, %d", i, j);
	}

	public void process(int[] ints) {
		System.out.println("Adding integer array:" + Arrays.toString(ints));
	}

	public void process(Object[] objs) {
		System.out.println("Adding integer array:" + Arrays.toString(objs));
	}
}

class MathProcessor extends Processor {

	@Override
	public void process(int i, int j) {
		System.out.println("Sum of integers is " + (i + j));
	}

	@Override
	public void process(int[] ints) {
		int sum = 0;
		for (int i : ints) {
			sum += i;
		}
		System.out.println("Sum of integer array elements is " + sum);
	}

}

覆寫

process() 方法和 int i, int j 參數在 Processor 中被子類別 MathProcessor 覆寫。第 7 行和第 23 行:

public class Processor {

    public void process(int i, int j) { /* ... */ }

}

/* ... */

class MathProcessor extends Processor {
 
    @Override
    public void process(int i, int j) {  /* ... */ }

}

Processor 中的 process() 方法和 int[] ints 也在子類別中被覆寫。第 11 行和第 28 行:

public class Processor {

    public void process(int[] ints) { /* ... */ }

}

/* ... */

class MathProcessor extends Processor {

    @Override
    public void process(Object[] objs) { /* ... */ }

}

重載

process() 方法在 Processor 類別中被重載。第 7、11 和 15 行:

public class Processor {

    public void process(int i, int j) { /* ... */ }

    public void process(int[] ints) { /* ... */ }

    public void process(Object[] objs) { /* ... */ }

}

結論

在本文中,我們涵蓋了Java中的覆寫和重載。當方法簽名在超類和子類中相同時,就會發生覆寫。當同一個類中的兩個或多個方法具有相同的名稱但不同的參數時,就會發生重載。

Source:
https://www.digitalocean.com/community/tutorials/overriding-vs-overloading-in-java