Java学习笔记-基础day-6-匿名对象

匿名对象的概述

什么是匿名对象:就是指"没有名字"的对象。

有名字的对象:
    Student stu = new Student();
    stu.study();
    
匿名对象:
	new Student();
	new Student().study();
使用匿名对象
  • 特点:匿名对象只能使用一次

  • 使用场景:方法的参数,方法的返回值

    public class Test {
        public static void main(String[] args) {
    
            // 创建对象
            Student stu1 = new Student("张三",18);// 有名字的对象
            stu1.show();
    
            //匿名对象
            new Student("张三",18).show();// 没有名字的对象
    
            System.out.println("==================================");
            
            // 调用method1方法
            Student stu2 = new Student("李四",18);// 0x11901
            method1(stu2);// 有名字的对象传参
            
            // 匿名对象的方式传参数
            method1(new Student("李四",18));
    
            System.out.println("==================================");
            Student stu3 = method2();// 0x11908
            stu3.show();// 王五,18
    
        }
     	// 匿名对象的方式传参数的方法
        public static void method1(Student stu){// 0x11901
            stu.show();
        }
        
     	//返回匿名对象的方法
        public static Student method2(){
            //Student stu = new Student("王五",18);// 0x11908
            //return stu;// 0x11908
    
            return new Student("王五",18);
        }
    
    }
    
    

小结

  • 匿名对象:就是指"没有名字"的对象。
  • 特点: 只能使用一次
  • 一定要注意使用场景
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值