AP计算机科学A(APcomputer science A)复习备考攻略视频教程
42866 人在学
今天在项目里做事,中午休息时间,补上这个教程吧。这次我们看看Overload 的内容 。
测试代码
package lession10;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* 老紫竹java基础培训(10),方法的Overload介绍.
* 匹配方式为最特殊匹配,或者叫最准确匹配
* 如果发现多个都有相同的匹配度,则编译报错。
*
(java2000.NET)
*
*/
public class Lession10 {
public void test1(byte id) {
System.out.println("test1(byte);");
}
public void test1(short id) {
System.out.println("test1(short);");
}
public void test1(int id) {
System.out.println("test1(int);");
}
public void test1(long id) {
System.out.println("test1(long);");
}
public void test1(float id) {
System.out.println("test1(float);");
}
public void test1(double id) {
System.out.println("test1(double);");
}
public void test2(Object o) {
System.out.println("test2(Object);");
}
public void test2(String o) {
System.out.println("test2(String);");
}
public void test2(Integer o) {
System.out.println("test2(Integer);");
}
public void test2(List o) {
System.out.println("test2(List);");
}
public void test2(ArrayList o) {
System.out.println("test2(ArrayList);");
}
public void test3(int a, float b) {
System.out.println("test3(int,float);");
}
public void test3(long a, double b) {
System.out.println("test3(long,double);");
}
public static void main(String[] args) {
Lession10 o = new Lession10();
o.test1(1); // 整数默认为 int
o.test1((byte) 1); // 强制调用 byte
o.test1((short) 1); // 强制调用 short
o.test1(1L); // long
o.test1(1.0); // 小数默认为 double
o.test1(1.0F); // 强制调用float
//
o.test2(new Object()); // 对象类型
o.test2("String"); // 字符串比对象更准确
o.test2(new Integer(3)); // 整数对象
o.test2(3); // JDk 5及以上
o.test2(new LinkedList()); // 调用更匹配的List
o.test2(new ArrayList()); // 调用 ArrayList
//
// 强制转换测试
o.test2((Object) new ArrayList()); // 以强制后的类型进行屁屁额
o.test2((List) new ArrayList());// 以强制后的类型进行屁屁额
// 多参数测试
o.test3(1, 2);
o.test3(1L, 3);
o.test3(1, 3D); // 自动升级优先,int可以自动升级到long,float可以自动升级到 double
//
// o.test2(null); // 不能确定匹配度的测试
}
}