Java中,当函数名相同时,会通过参数的类型、个数等判断具体调用哪个函数,换句话说就是,函数名可以不是唯一,只要参数类型、个数有不相同的即被判定为两个不同的函数。
但一般实战中不建议这么做,正确的设定函数名可以为阅读代码的人带来很多便利。
此处给出如下的代码,测试结果正确,编译器会根据参数的类型和个数来调用正确的函数。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ch05_14;
/**
*
* @author
*/
public class Ch05_14 {
static int jia(int a,int b)
{ return(a+b);}
static double jia(double a,double b)
{ return(a+b);}
static int jia(int a,int b,int c)
{ return(a+b+c);}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("sum1为"+jia(4,2));
System.out.println("sum2为"+jia(4.5,2.5));
System.out.println("sum3为"+jia(4,2,3));
// TODO code application logic here
}
}