在Java中,通常如何实现方法重载

时间:2018-01-23 07:39:35

标签: java methods overloading

我正在使用ANTLR4编写一个解析器,它接受一些带参数的函数表达式。参数可以是Stringintdouble和函数表达式本身。

问题是我想支持具有不同签名但具有相同名称(即重载)的函数。因此解析器可以成功解析以下表达式:

sum(hash('some_string'), 2, 3)

sum(hash('some_string'), 2)

我不想接受var-args,但只接受2和3个参数。有人能让我了解如何实现重载。特别是javac如何实现它?

1 个答案:

答案 0 :(得分:1)

编译器将根据作为参数传递的数据类型知道代码需要哪个重载方法。 sum()方法的重载示例

public String sum(String hashString, int intValue, double dblValue) {
    // method code here....
    return result;
}

public String sum(String hashString, double dblValue, int intValue) {
    // method code here....
    return result;
}

public String sum(String hashString, int intValue) {
    // method code here....
    return result;
}

public String sum(String hashString, double dblValue) {
    // method code here....
    return result;
}

public String sum(String hashString, int... intValue) {
    // intValue is optional, one or more can be supplied or
    // an array of int's can be supplied. As examples....

    int intParam = 0;
    if (intValue.length > 0) {
        intParam = intValue[0];  
    }
    // method code here....

    //        OR (remove the above)

    int intParam1 = 0, intParam2 = 0;
    if (intValue.length > 0) {
        if (intValue.length >= 1) { intParam1 = intValue[0]; }
        if (intValue.length >= 2) { intParam2 = intValue[1]; }
    }
    // method code here....

    //        OR (remove the above)

    for (int i = 0; i < intValue.length; i++) {
        int intParam = intValue[i];
        // method code here....
    }

    //        OR (remove the above)

    // whatever other way you want to handle the
    // supplied optional arguments.
    // Method code here....
    return result;
}

public String sum(String hashString, double... dblValue) {
    // dblValue is optional, one or more can be supplied or
    // an array of double's can be supplied. 
    // method code here....
    return result;
}

etc., etc....