• 什么是匿名对象

    没有对象名接收的对象,我们称为匿名对象

    • 匿名对象的使用方法(匿名对象只能使用一次)

    (1)匿名对象直接调用成员方法
    (2)匿名对象直接当做方法参数传递
    (3)匿名对象直接当做返回值

    1. public class Test01 {
    2. public static void main(String[] args) {
    3. //1.直接调用方法
    4. new Student().show();
    5. //2.做为方法的参数传递
    6. userStudent(new Student());
    7. }
    8. public static void userStudent(Student s){
    9. }
    10. //方法的返回值类型是一个类,那么此方法需要返回此类的对象
    11. public static Student getStudent(){
    12. //3.作为方法的返回值
    13. return new Student();
    14. }
    15. }
    16. class Student{
    17. public void show(){
    18. System.out.println("Student类中的show方法执行了");
    19. }
    20. }
    • 代码实践:注册案例

    package com.itheima.anonymous;
    /需求 : 1 创建用户(User)对象 , 对象数据采用键盘录入而来
    2 用户(User)包含的属性 :
    用户名 (username)
    手机号码 (phonNumber)
    登录密码 (password)
    确认密码 (confirm)
    电子邮箱 (email)
    性别 (sex)
    出生日期 (birthday)
    3 如果登录密码和确认密码不一致 , 重新输入
    4 把用户(User)对象 ,添加到ArrayList集合中 , 打印集合对象即可
    /

    1. import java.util.ArrayList;
    2. import java.util.Scanner;
    3. public class Test02 {
    4. public static void main(String[] args) {
    5. //键盘录入
    6. Scanner sc = new Scanner(System.in);
    7. //创建集合对象
    8. ArrayList<User> list = new ArrayList<>();
    9. for (int i = 1; i <= 3; i++) {
    10. System.out.println("请输入第" + i + "个用户的用户名");
    11. String name = sc.nextLine();
    12. System.out.println("请输入第" + i + "个用户的登录密码");
    13. String password = sc.nextLine();
    14. System.out.println("请确认第" + i + "个用户的登录密码");
    15. String confirm = sc.nextLine();
    16. //比较登录密码和确认密码是否相同
    17. if (password.equals(confirm)) {
    18. //创建用户对象
    19. User user = new User(name, password, confirm);
    20. //把用户对象添加到集合中
    21. list.add(user);
    22. System.out.println("登录成功");
    23. } else {
    24. System.out.println("输入信息错误!");
    25. i--;
    26. }
    27. }
    28. }
    29. }

    用户类

    1. package com.itheima.anonymous;
    2. public class User {
    3. private String username;
    4. private String password;
    5. private String confirm;
    6. public User() {
    7. }
    8. public User(String username, String password, String confirm) {
    9. this.username = username;
    10. this.password = password;
    11. this.confirm = confirm;
    12. }
    13. public String getUsername() {
    14. return username;
    15. }
    16. public void setUsername(String username) {
    17. this.username = username;
    18. }
    19. public String getPassword() {
    20. return password;
    21. }
    22. public void setPassword(String password) {
    23. this.password = password;
    24. }
    25. public String getConfirm() {
    26. return confirm;
    27. }
    28. public void setConfirm(String confirm) {
    29. this.confirm = confirm;
    30. }
    31. }