Java中匿名对象是什么意思啊?

2025-05-20 00:33:51
推荐回答(2个)
回答(1):

    匿名对象使用方法一:当对对象的方法只调用一次时,可以用匿名对象来完成,这样写比较简化。

    如果对一个对象进行多个成员的调用,就必须给这个对象起个名字。

    匿名对象使用方法二:可以将匿名对象作为实际参数进行传递。

    如下代码所示:

class Person {
    private String name;
    private int age;
    public Person() {
    }
    public Person(String name) {
        this.name = name;
    }
    public Person(String name, int age) {
        this.setName(name);
        this.setAge(age);
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return this.name;
    }
    public void setAge(int age) {
        if (age > 0 && age < 140) {
            this.age = age;
        }
    }
    public int getAge() {
        return this.age;
    }
    public void tell() {
        System.out.println("姓名:" + this.getName() + ",年龄:" + this.getAge());
    }
}
public class Test {
    public static void main(String args[]) {
        new Person("张三", 46).tell();//通过匿名对象调用方法
    }
}

回答(2):

java匿名对象,即没有名字的对象;
如果存在Book类:
则 new Book();就是一个匿名对象。