匿名对象
public class InstanceTest {
public static void main(String[] args) {
Phone p = new Phone();
System.out.println(p); //com.klvchen.java.Phone@3b6eb2ec
p.sendEmail(); //发送邮件
p.playGame(); //玩游戏
//匿名对象
new Phone().sendEmail(); //发送邮件
new Phone().playGame(); //玩游戏
new Phone().price = 1999;
new Phone().showPrice(); //0.0
PhoneMall mall = new PhoneMall();
mall.show(new Phone()); //发送邮件
//玩游戏
}
}
class PhoneMall{
public void show(Phone phone) {
phone.sendEmail();
phone.playGame();
}
}
class Phone{
double price; //价格
public void sendEmail() {
System.out.println("发送邮件");
}
public void playGame() {
System.out.println("玩游戏");
}
public void showPrice() {
System.out.println(price);
}
}
方法重载
定义:在同一个类中,允许存在一个以上的同名方法,只要他们的参数个数或参数类型不同即可。
"两同一不同":同一个类、相同方法名;参数列表不同,参数个数不同,参数类型不同
判断是否重载:跟方法的权限修饰符,返回值类型,形参变量名,方法体都没有关系。
在通过对象调用方法时,如果确定某一个指定的方法: 方法名 ---> 参数列表
public class OverLoadTest {
public static void main(String[] args) {
OverLoadTest test = new OverLoadTest();
test.getSum(1, 2); //1
}
//如下的4个方法构成了重载
public void getSum(int i, int j) {
System.out.println("1");
}
public void getSum(double d1, double d2) {
System.out.println("2");
}
public void getSum(String s, int i) {
System.out.println("3");
}
public void getSum(int i, String s) {
System.out.println("4");
}
}
可变个数的形参
JavaSE 5.0 中提供了 Varargs(variable number of argumants)机制,允许直接定义能喝多个实参相匹配的形参。从而,可以用一种更简单的方式,来传递个数可变的实参。
// JDK 5.0 以前:采用数组形参来定义方法,传入多个同一类型变量
public static void test(int a, String[] books);
// JDK 5.0: 采用可变个数形参来定义方法,传入多个同一个类型变量
public static void test(int a, String ... books);
具体使用:
- 当调用可变个数形参的方式时,传入的参数个数可以是:0个,1个,2个。。。
- 可变个数形参的方法与本类中方法名相同,形参不同的方法直接构成重载
- 可变个数形参的方法与本类中方法名相同,形参类型也相同的数组之间不构成重载,换句话说,二者不能共存
- 可变个数形参在方法的形参中,必须声明在末尾
- 可变个数形参在方法的形参中,最多只能声明一个可变形参
public class MethodArgsTest {
public static void main(String[] args) {
MethodArgsTest test = new MethodArgsTest();
test.show(12); // show(int)
test.show("hello"); // show(String)
test.show("hello","world"); // show(String ... strs)
test.show(); // show(String ... strs)
}
public void show(int i) {
System.out.println("show(int)");
}
public void show(String s) {
System.out.println("show(String)");
}
public void show(String ... strs) {
System.out.println("show(String ... strs)");
}
}