介绍
Overriding 和 overloading 是 Java 编程的核心概念,它们是我们 Java 程序中实现多形态的途径,多形态是 OOPS 概念(/社区/教程/oops-concepts-java-example)之一。
当方法签名(名称和参数)在超级类和儿童类相同时,它被称为 overriding. 当同一类中的两个或多个方法具有相同的名称但不同的参数时,它被称为 overloading。
超载和超载的比较
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程序中的过载和过载的例子:
1package com.journaldev.examples;
2
3import java.util.Arrays;
4
5public class Processor {
6
7 public void process(int i, int j) {
8 System.out.printf("Processing two integers:%d, %d", i, j);
9 }
10
11 public void process(int[] ints) {
12 System.out.println("Adding integer array:" + Arrays.toString(ints));
13 }
14
15 public void process(Object[] objs) {
16 System.out.println("Adding integer array:" + Arrays.toString(objs));
17 }
18}
19
20class MathProcessor extends Processor {
21
22 @Override
23 public void process(int i, int j) {
24 System.out.println("Sum of integers is " + (i + j));
25 }
26
27 @Override
28 public void process(int[] ints) {
29 int sum = 0;
30 for (int i : ints) {
31 sum += i;
32 }
33 System.out.println("Sum of integer array elements is " + sum);
34 }
35
36}
超越
在处理器
中的process()
方法和int i, int j
参数在MathProcessor
儿童类别中被覆盖。
1public class Processor {
2
3 public void process(int i, int j) { /* ... */ }
4
5}
6
7/* ... */
8
9class MathProcessor extends Processor {
10
11 @Override
12 public void process(int i, int j) { /* ... */ }
13
14}
在处理器
中的process()
方法和int[] ints
也被覆盖在儿童类中。
1public class Processor {
2
3 public void process(int[] ints) { /* ... */ }
4
5}
6
7/* ... */
8
9class MathProcessor extends Processor {
10
11 @Override
12 public void process(Object[] objs) { /* ... */ }
13
14}
超载
process()
方法在 Processor
类中过载. 行 7, 11 和 15:
1public class Processor {
2
3 public void process(int i, int j) { /* ... */ }
4
5 public void process(int[] ints) { /* ... */ }
6
7 public void process(Object[] objs) { /* ... */ }
8
9}
结论
在本文中,我们讨论过载和过载在Java中。过载发生在方法签名在超级类和儿童类中相同时。