JAVA基础(匿名对象)

1,什么是匿名对象

  • 没有名字的对象

 

2,匿名对象应用场景

  • 调用方法,仅仅只调用一次的时候。

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

 

3,匿名调用有什么好处

  • 节省代码,但是调用多次的时候,不适合。匿名对象调用完毕就是垃圾。可以被垃圾回收器回收。

 

4,匿名对象调用

【1】注意事项

  • 匿名对象只适合对方法的一次调用,因为调用多次就会产生多个对象,不如用有名字的对象    

  • 匿名对象可以调用属性,但是没有意义,因为调用后就变成垃圾,  如果需要赋值还是用有名字对象

class Demo2_Car {

    public static void main(String[] args) {

        /*Car c1 = new Car();            //创建有名字的对象

        c1.run();

        c1.run();





        new Car().run();            //匿名对象调用方法

        new Car().run();    */        //匿名对象只适合对方法的一次调用,因为调用多次就会产生多个对象,不如用有名字的对象    

    

        //匿名对象是否可以调用属性并赋值?有什么意义?

        /*

        匿名对象可以调用属性,但是没有意义,因为调用后就变成垃圾

        如果需要赋值还是用有名字对象

        */

        new Car().color = "red";

        new Car().num = 8;

        new Car().run();

    }

}





class Car {

    String color;            //颜色

    int num;                //轮胎数





    public void run() {

        System.out.println(color + "..." + num);

    }

}



 

 

5,方法中形式参数是匿名对象

  • 理解

class Demo1_Student {

    public static void main(String[] args) {

        print(10);





        Student s = new Student();                    //创建对象,并将对象的地址值赋值给s

        print(s);

    }





    public static void print(int x) {                //基本数据类型当作形式参数

        System.out.println(x);

    }





    public static void print(Student stu) {            //引用数据类型当作形式参数

                                // Sudent stu = s(0x0011)

        stu.name = "张三";

        stu.age = 23;

        stu.speak();

    }

}





/*

* A:方法的参数是类名public void print(Student s){}//print(new Student());

    * 如果你看到了一个方法的形式参数是一个类类型(引用类型),这里其实需要的是该类的对象。

*/

class Student {

    String name;                    //姓名

    int age;                        //年龄





    public void speak() {

        System.out.println(name + "..." + age);

    }

}

6,匿名对象提高代码复用性

class Demo3_Car {

    public static void main(String[] args) {

        //Car c1 = new Car();

        /*c1.color = "red";

        c1.num = 8;

        c1.run();*/

        //method(c1);



        method(new Car());





        //Car c2 = new Car();

        //method(c2);

        method(new Car());                //匿名对象可以当作参数传递

    }





    //抽取方法提高代码的复用性

    public static void method(Car cc) {    //Car cc = new Car();

        cc.color = "red";

        cc.num = 8;

        cc.run();

    }

}





class Car {

    String color;            //颜色

    int num;                //轮胎数





    public void run() {

        System.out.println(color + "..." + num);

    }

}









 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

兴帅_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值