Java-匿名对象

一、匿名对象

  • 当对象对方法仅进行一次调用,可简化成匿名对象
  • 匿名对象即没有引用类型的对象,
    • 匿名: new Person();
    • 正常:Person p = new Person();
  • 匿名对象可以作为实际参数进行传递
    • 传递:show方法传入Person对象,show(new Person());

二、代码

package com.nsys.demo02;

/**
 * @Author nsys
 * @Date 2021/11/7 15:45
 * @Description
 */
public class Demo8 {
    int count = 9;

    public void count1() {
        count = 10;
        System.out.println(count);
    }

    public void count2() {
        System.out.println(count++);
    }

    public static void main(String[] args) {
        // new Demo8是匿名对象,匿名对象使用后就不能再使用了
        new Demo8().count1();

        Demo8 d = new Demo8();
        d.count2();
        d.count2();
        /*
        结果:
        10
        9
        10
         */
    }
}
posted @ 2021-11-07 15:55  难删亦删  阅读(331)  评论(1)    收藏  举报