灌篮少年 发表于 2023-5-21 15:30:27

Java面向对象中“匿名对象”的使用

1.0 匿名对象的基本知识


[*]匿名对象
顾名思义,匿名对象指的就是没有名字的对象,在使用中理解为实例化一个类对象,但是并不把它赋给一个对应的类变量,而是直接使用。在理解匿名对象前,我们先创建一个类便于后面的使用。
[*]匿名对象具有以下特征:
语法上:只创建对象,但不用变量来接收,例如:假设现在Student类如上所示,通常情况我们在使用这个类时需要先实例化类对象,然后调用类的属性和方法
[*]匿名对象的使用:
匿名对象本质上仍然是一个对象,所以它具备对象的所有功能
每次创建一个匿名对象都是一起全新的对象,即每次创建的匿名对象都是不同的对象,它们在堆内存中具有不同的地址。而且一个匿名对象只能使用一次。
缺点:
一个匿名对象只能使用一次,造成内存空间的浪费。
优点:
由于匿名对象不需要在实例化后赋给变量,因此当大量需要使用匿名对象时,可以节省保存变量所需的栈空间
JVM的垃圾回收会根据对象是否可达来判断是否为垃圾,如果不可达,则在下一次的垃圾回收中进行回收。而匿名对象创建后只能使用一次,当使用结束后它就是垃圾了,这样便于JVM快速回收,节省堆内存空间。
2.0 通过实验代码进行匿名对象的学习

2.1

写一个名为Account的类模拟账户。该类的属性和方法如下图所示。
该类包括的属性:账号id,余额balance,年利率annualInterestRate;
包含的方法:访问器方法(getter和setter方法),取款方法withdraw(),存款方法deposit()。
https://img2023.cnblogs.com/blog/3180465/202305/3180465-20230521151539259-539101931.png
2.2

创建Customer类。
https://img2023.cnblogs.com/blog/3180465/202305/3180465-20230521151554677-630923263.png
a. 声明三个私有对象属性:firstName、lastName和account。
b. 声明一个公有构造器,这个构造器带有两个代表对象属性的参数(f和l)
c. 声明两个公有存取器来访问该对象属性,方法getFirstName和getLastName返回相应的属性。
d. 声明setAccount 方法来对account属性赋值。
e. 声明getAccount 方法以获取account属性。
2.3

写一个测试程序。
(1)
创建一个Customer ,名字叫 Jane Smith, 他有一个账号为1000,余额为2000元,年利率为 1.23% 的账户。
(2)
对Jane Smith操作。
存入 100 元,再取出960元。再取出2000元。
打印出Jane Smith 的基本信息
https://img2023.cnblogs.com/blog/3180465/202305/3180465-20230521151647288-1079905184.png
3.0 代码实现

3.1 Account.java

package classTest.Account;

// 虚拟账户练习
public class Account {
    private int id; //账号
    private double balance; //余额
    private double Rate; //年利率

    public Account(int i, double b, double a){
      id = i;
      balance = b;
      Rate = a;
    }

    public int getId() {
      return id;
    }

    public double getBalance() {
      return balance;
    }

    public double getRate() {
      return Rate;
    }

    public void setId(int id) {
      this.id = id;
    }

    public void setBalance(double balance) {
      this.balance = balance;
    }

    public void setRate(double rate) {
      Rate = rate;
    }

    public void withdraw(double amount){ //取钱
      if(amount <= 0){
            System.out.println("输入金额不合法");
      }
      else if(amount > balance){
            System.out.println("余额不足");
      }
      else {
            System.out.println("取钱成功: " + amount);
            balance -= amount;
      }
    }

    public void deposit(double amount){ //存钱
      if(amount > 0){
            balance += amount;
            System.out.println("成功存入:" + amount);
      }
      else{
            System.out.println("数据不合法");
      }

    }
}3.2 Customer.java

package classTest.Account;

public class Customer {
    private String firstName;
    private String lastName;
    private Account account;

    public Customer(String f, String l){
      firstName = f;
      lastName = l;
    }

    public String getFirstName() {
      return firstName;
    }

    public String getLastName() {
      return lastName;
    }

    public Account getAccount() {
      return account;
    }

    public void setFirstName(String firstName) {
      this.firstName = firstName;
    }

    public void setLastName(String lastName) {
      this.lastName = lastName;
    }

    public void setAccount(Account account) {
      this.account = account;
    }
}3.3 测试程序CustomerTest.java

package classTest.Account;

import java.util.concurrent.CountDownLatch;

public class AccountTest {
    public static void main(String[] args) {
      // Customer实例
      Customer cus = new Customer("Jane", "Smith");
      // Account实例
      Account ac = new Account(1000, 2000, 0.0123);

      // 客户和账户取得联系
      cus.setAccount(ac);

//      cus.setAccount(new Account(1000, 2000, 0.0123)); // 也可以直接这样写 -> 匿名对象

//      ac.deposit(100);
//      ac.withdraw(960);
//      ac.withdraw(2000);

      cus.getAccount().deposit(100);
      cus.getAccount().withdraw(960);
      cus.getAccount().withdraw(2000);

      System.out.println(cus.getFirstName() + " " + cus.getLastName() + " has a account id: " + ac.getId() + ", annualInterestRate is " + ac.getRate() + ", balance is " + ac.getBalance());

    }
}4.0总结

可以看出可以直接使用
cus.setAccount(new Account(1000, 2000, 0.0123));来进行匿名对象的定义

[*]1.匿名对象只能使用一次
[*]2.匿名对象往往作为形参传递给方法的实参

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Java面向对象中“匿名对象”的使用