标签:
/*
需求:求数的和
需求不断的发生改变,就对应的提供了多个求和的方法。
但是名字是不一样的。
又要求方法命名做到:见名知意。
但是,很明显,现在没有做到。
针对这种情况:方法的功能相同,参数列表不同的情况,为了见名知意,Java允许它们起一样的名字。
其实,这种情况有一个专业名词:方法重载。
方法重载:
在同一个类中,方法名相同,参数列表不同。与返回值类型无关。
参数列表不同:
A:参数个数不同
B:参数类型不同
*/
class FunctionDemo4 {
public static void main(String[] args) {
// jvm会根据不同的参数去调用不同的功能
System.out.println(sum(10, 20));
System.out.println(sum(10, 20, 30));
System.out.println(sum(10, 20, 30, 40));
System.out.println(sum(10.5f, 20f));
}
// 需求1:求两个数的和
public static int sum(int a, int b) {
System.out.println("int");
return a + b;
}
//需求2:求三数的和
/*
public static int sum1(int a,int b,int c) {
return a + b + c;
}
*/
public static int sum(int a, int b, int c) {
return a + b + c;
}
//需求3:求四个数的和
/*
public static int sum2(int a,int b,int c,int d) {
return a + b + c + d;
}
*/
public static int sum(int a, int b, int c, int d) {
return a + b + c + d;
}
public static float sum(float a, float b) {
System.out.println("float");
return a + b;
}
}
/*
比较两个数据是否相等。参数类型分别为
两个byte类型,两个short类型,两个int类型,两个long类型,
并在main方法中进行测试
*/
class FunctionTest6 {
public static void main(String[] args) {
// 测试
byte b1 = 3;
byte b2 = 4;
System.out.println("byte:" + compare(b1, b2));
// 测试
short s1 = 5;
short s2 = 5;
System.out.println("short:" + compare(s1, s2));
// 后面的两个自己测试
}
// byte类型
public static boolean compare(byte a, byte b) {
System.out.println("byte");
return a == b;
}
// short类型
public static boolean compare(short a, short b) {
System.out.println("short");
return a == b;
}
// int类型
public static boolean compare(int a, int b) {
System.out.println("int");
return a == b;
}
// long类型
public static boolean compare(long a, long b) {
System.out.println("long");
return a == b;
}
}
标签:
原文地址:http://my.oschina.net/u/2001589/blog/499875