Java学习笔记----匿名对象

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/oampZuo12345/article/details/48862759
  • 匿名对象的概念
  • 匿名对象的应用场景

匿名对象的概念

匿名对象顾名思义就是没有名字的对象。JAVA匿名对象会被分配到堆内存,分配到内存后运行一次就变成垃圾了,不过内存处理机制会对一定时间内无指针指向的对象进行 destrory()。

匿名对象的应用场景

1、调用方法,仅仅只调用一次的时候
注意:调用多次的时候,不合适。
好处: 匿名对象调用完毕就是垃圾,可以被垃圾回收器回收。

2、匿名对象可以作为实际参数传递

class Student {
    public void show() {
        System.out.println("我爱学习");
    }
}

class StudentDemo {
    public void method(Student s) {
        s.show();
    }
}

class NoNameDemo {
    public static void main(String[] args) {
        //带名字的调用
        Student s = new Student();
        s.show();
        s.show();
        System.out.println("--------------");

        //匿名对象
        //new Student();
        //匿名对象调用方法
        new Student().show();
        new Student().show(); //这里其实是重新创建了一个新的对象
        System.out.println("--------------");


        //匿名对象作为实际参数传递
        StudentDemo sd = new StudentDemo();
        //Student ss = new Student();
        //sd.method(ss); //这里的ss是一个实际参数
        //匿名对象
        sd.method(new Student());

        //再来一个
        new StudentDemo().method(new Student());
    }
}

猜你喜欢

转载自blog.csdn.net/oampZuo12345/article/details/48862759