匿名对象:没有名字的对象
.
使用情景:确定一个对象只需要使用唯一的一次
使用格式:
(1) new 类名();
(2) new 类名().实例变量;
(3) new 类名().实例方法;
1.使用匿名对象调用实例变量和实例方法
public class Student{
String name;
public void study(){
System.out.println("学习");
System.out.println("姓名:"+name);
}
}
public class Test {
public static void main(String[] args) {
//创建有名字的对象
Student s = new Student();
s.name = "张三";
s.study();
//创建匿名对象
new Student().name = "李四";//匿名对象调用属性
new Student().study();//匿名对象调用方法
}
}
注意事项:
1.匿名对象可以
调用属性
但是没有意义
2.如果需要赋值
,就不要使用匿名对象
2.使用匿名对象向方法传递参数
public class Test2 {
public static void main(String[] args) {
//正常方式传递参数
/*
Student s = new Student();
param(s);
*/
//使用匿名对象传递参数
mParam(new Student());
}
public static void mParam(Student s){
System.out.println("已经使用匿名对象传递参数!");
}
}
3.使用匿名对象作为方法的返回值
public class Test3 {
public static void main(String[] args) {
mReturn();
}
public static Student mReturn(){
//正常方式作为返回值
/*
Student s = new Student();
return s;
*/
//使用匿名对象作为返回值
System.out.println("已经使用匿名对象作为返回值!");
return new Student();
}
}