匿名对象
- 匿名对象的概述
正常对象:
类名称 变量名 = new 类名称();
匿名对象:
new 类名称();
匿名对象的使用:
new 类名称().成员变量 =xxx;
new 类名称().成员方法();
匿名对象只能使用一次,下次在调用不会受上次的影响;
package day1012;
public class anonymous {
public static void main(String[] args) {
Person one = new Person();
one.name="张丹";
one.showName();
new Person().name="李四";
new Person().showName();
}
}
- 匿名对象作为方法的返回值和参数
匿名对象作为方法的参数:
package day1012;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
one(new Scanner(System.in)); 调用方法,匿名对象作为方法的参数
}
public static void one(Scanner sc) { 创建方法,参数类型为Scanner
int num = sc.nextInt();
System.out.println("输入的是"+num);
}
}
匿名对象作为方法的返回值:
package day1012;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
one(new Scanner(System.in));
System.out.println("输入的是"+two().nextInt());
}
public static void one(Scanner sc) {
System.out.println("输入的是"+ sc.nextInt());
}
public static Scanner two(){
return new Scanner(System.in);
}
}