匿名对象
1.匿名对象的定义
- 什么是匿名对象?
没有名字的对象就是匿名对象
2.匿名对象的格式
- 匿名对象的格式?
new 类名();
new Person();
3.匿名对象的特点
- 一次性
- 只能使用一次
匿名对象的使用
public class Person {
String name;
// 构造方法
public Person(String name) {
this.name = name;
}
// 吃的方法
public void eat() {
System.out.println(name + "正在吃饭");
}
public static void main(String[] args) {
// 使用匿名对象创建一个人
new Person("John").eat();
// 使用匿名对象创建另一个人
new Person("Alice").eat();
}
}
-
匿名对象什么时候可以使用?
当我们只需要使用一次对象的属性或者方法的时候,就可以选择使用匿名对象 -
匿名对象可以作为实际参数进行传递
public class Person {
String name;
// 构造方法
public Person(String name) {
this.name = name;
}
// 吃的方法
public void eat() {
System.out.println(name + "正在吃饭");
}
// 欢迎方法,接受一个 Person 对象作为参数
public void welcome(Person person) {
System.out.println("欢迎 " + person.name);
}
public static void main(String[] args) {
// 创建一个 Person 对象并调用 eat 方法
new Person("John").eat();
// 使用匿名对象作为实际参数传递给 welcome 方法
new Person("Alice").welcome(new Person("Bob"));
}
}