Java 重载
原文: https://javabeginnerstutorial.com/core-java-tutorial/overloading/
重载方法为您提供了一个选项,可以在类中使用与相同的方法名称,但具有不同的参数。
Java 方法规则中的重载
有一些与重载方法相关的规则。
重载方法
- 必须更改参数列表
- 可以更改返回类型
- 可以更改访问修饰符(更广泛)
- 可以声明一个新的或更广泛的受检异常
方法可以在类或子类中重载。
重载方法示例
//Overloaded method with one argumentpublic void add(int input1, int input2) {System.out.println("In method with two argument");}//Overloaded method with one argumentpublic void add(int input1) {System.out.println("In method with one argument");}
调用重载方法
在几种可用的重载方法中,调用的方法基于参数。
add(3,4);add(5);
第一个调用将执行第一个方法,第二个调用将执行第二个方法。
引用类型而不是对象决定调用哪个重载方法,和覆盖方法相反。
感谢 Manoj 指出拼写错误。
方法重载备忘单
- 使用相同的方法名称但使用不同的参数称为重载。
- 构造器也可以重载
- 重载的方法必须设置不同的参数。
- 重载的方法可能具有不同的返回类型。
- 重载的方法可能具有不同的访问修饰符。
- 重载的方法可能抛出不同的异常,更宽或更窄的没有限制。
- 超类中的方法也可以在子类中重载。
- 多态适用于覆盖和重载。
- 基于引用类型,确定在编译时间上确定将调用哪个重载方法。
方法重载示例
package com.overloading;/** Here we will learn how to overload a method in the same class.* Note: Which overloaded method is to invoke is depends on the argument passed to method.*/public class MethodOverloading {public static void main(String args[]){//Creating object of the class MethodOverloadingMethodOverloading cls = new MethodOverloading();System.out.println("calling overloaded version with String parameter");cls.method("Hello");System.out.println("calling overloaded version with Int parameter");cls.method(3);/** Here same method name has been used, But with different argument.* Which method is to invoke is decided at the compile time only*/}/** Overloaded version of the method taking string parameter* name of the method are same only argument are different.*/void method(String str){System.out.println("Value of the String is :"+str);}/** Overloaded version taking Integer parameter*/void method(int i){System.out.println("Value of the Int is :"+i);}}
- 使用相同的方法名称但使用不同的参数称为重载。
- 构造器也可以重载
- 重载的方法必须设置不同的参数。
- 重载方法可能具有不同的返回类型。
- 重载的方法可能具有不同的访问修饰符。
- 重载的方法可能会抛出不同的异常,更宽或更窄的没有限制。
- 超类中的方法也可以在子类中重载。
- 多态适用于覆盖和重载。
- 基于引用类型,确定在编译时确定将调用哪个重载方法。
