【Java每日一题】— —第二十三题:匿名对象及其使用问题(2023.10.07)

🕸️Hollow,各位小伙伴,今天我们要做的是第二十三题。

🎯问题:

匿名对象的应用场景如下:

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

注意:调用多次的时候,不适合。

那么,这种匿名调用有什么好处吗?

有,匿名对象调用完毕就是垃圾。

B:匿名对象可以作为实际参数传递给形式参数,相当于赋值语句。

🎯答案:

java 复制代码
package cn.num03;
public class NoNameDemo {
	public static void main(String[] args) {
		Student s=new Student();
		s.show();
		s.show();
		System.out.println("----匿名对象的调用----");
		//匿名对象的调用
		//A:调用方法,仅仅只调用一次的时候。
		new Student().show();
		System.out.println("-----匿名对象作为实际参数传递---------");
		StudentDemo sd=new StudentDemo();
		//B:匿名对象可以作为实际参数传递
		sd.method(new Student());
		//再玩一个更特别的,该代码包括了匿名对象的两个应用场景
		new StudentDemo().method(new Student());	
	}
} 
package cn.num03;
public class Student {
	public void show() {
		System.out.println("我们爱Java!");
	}
} 
package cn.num03;
public class StudentDemo {
	public void method(Student s) {
		s.show();
	}
}
相关推荐
28岁青春痘老男孩4 小时前
JDK8+SpringBoot2.x 升级 JDK 17 + Spring Boot 3.x
java·spring boot
方璧4 小时前
限流的算法
java·开发语言
元Y亨H4 小时前
Nacos - 服务注册
java·微服务
Hi_kenyon4 小时前
VUE3套用组件库快速开发(以Element Plus为例)二
开发语言·前端·javascript·vue.js
曲莫终4 小时前
Java VarHandle全面详解:从入门到精通
java·开发语言
一心赚狗粮的宇叔4 小时前
中级软件开发工程师2025年度总结
java·大数据·oracle·c#
奋进的芋圆5 小时前
DataSyncManager 详解与 Spring Boot 迁移指南
java·spring boot·后端
ghie90905 小时前
基于MATLAB GUI的伏安法测电阻实现方案
开发语言·matlab·电阻
Gao_xu_sheng5 小时前
Inno Setup(专业安装/更新 EXE)
开发语言