Java 中方法重载有哪些限制?
当一个类有两个或多个名称相同但参数不同的方法时,在调用时,根据传递的参数调用相应的方法(或相应的方法体将动态地绑定到调用行)。这种机制被称为**方法重载**。
示例
class Test{
public int division(int a, int b){
int result = a/b;
return result;
}
public double division (float a, float b){
double result = a/b;
return result;
}
}
public class OverloadingExample{
public static void main(String args[]){
Test obj = new Test();
System.out.println("division of integers: "+obj.division(100, 40));
System.out.println("division of floating point numbers: "+obj.division(214.225f, 50.60f));
}
}输出
division of integers: 2 division of floating point numbers: 4.233695983886719
方法重载需要遵循的规则
在重载时,您需要牢记以下几点:
- 两种方法都应该在同一个类中。
- 方法的名称应该相同,但它们应该具有不同的参数数量或类型。
如果名称不同,它们将成为不同的方法,如果它们具有相同的名称和参数,则会抛出编译时错误,提示“方法已定义”。
示例
class Test{
public int division(int a, int b){
int result = a/b;
return result;
}
public double division (int a, int b){
double result = a/b;
return result;
}
}编译时错误
OverloadingExample.java:6: error: method division(int, int) is already defined in class Test
public static double division (int a, int b){
^
1 error在重写中,如果两种方法都遵循以上两条规则,则它们可以:
- 具有不同的返回类型。
示例
class Test{
public int division(int a, int b){
int result = a/b;
return result;
}
public void division (float a, float b){
double result = a/b;
System.out.println("division of floating point numbers: "+result);
}
}- 具有不同的访问修饰符:
class Test{
public int division(int a, int b){
int result = a/b;
return result;
}
private void division (float a, float b){
double result = a/b;
System.out.println("division of floating point numbers: "+result);
}
}- 可以抛出不同的异常:
class Test{
public int division(int a, int b)throws FileNotFoundException{
int result = a/b;
return result;
}
private void division (float a, float b)throws Exception{
double result = a/b;
System.out.println("division of floating point numbers: "+result);
}
}
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP