example
Designing a simple calculator class Calculator, deepen understanding of method overloading.
l may be made common arithmetic modulo operation on various numeric data types.
l is a must addition, other optional operation. The following rules addition (sum) for example.
l may be two identical byte short int long float double adding type data, returns the result of same type as the addend.
l of the sum (int, int) method to expand, it may be two or more, the number of unknown operand summation. For example, two integer summation, summed 100 integers, x integer summation.
public class Calcullator {
public static void main(String[] args) {
int a = 1;
int b = 2;
System.out.println(sum(a, b, 3, 4, 5));
System.out.println(sum(1L, 2L));
}
//对至少两个操作数进行求和运算。剩余个数未知的参数,它的本质是一个数组
public static int sum(int a, int b, int...orthers) {
int sum = a + b;
//对orthers参数进行判断,如果非空,遍历这个数组,把各个操作数累加到sum
if(orthers != null && orthers.length > 0) {
for (int i : orthers) {
sum += i;
}
}
return sum;
}
public static long sum(long a, long b) {
return a + b;
}
public static float sum(float a, float b) {
return a + b;
}
public static double sum(double a, double b) {
return a + b;
}
public static short sum(short a, short b) {
//整数的算数+操作符默认按照int类型运算,结果也是int类型,所以要强转为short类型
return (short) (a + b);
}
Sui Suinian aspects :
1. the number of unknown parameters calculation:
int a, int b, int…orthers
2.foreach:
for (int I: orthers) {
SUM = I +;
}
3. array length represented by:Array name .length
4. casts