对象属性使用——clone

以对象作为私有属性居然会自行变化??

类包含的实例字段属于某个类类型,这种情况相信大家都见到过。

通常,该实例字段设置为private,类方法中含有对其get,set方法。

有个类将其他类作为自己的私有属性,该类没有使用set方法,私有属性类对象居然就发生了变化,可不可怕,例子如下

public class test {
    public static void main(String[] args) {
        Account account = new Account(100,123);
        PeopleX xiaowai = new PeopleX("xiaowai");
        xiaowai.setAccount(account);
        // 这时候xiaowai这个人已经有自己的账户了,余额有100块
        Account cracker = xiaowai.getAccount();
        // cracker 有获取其他账户信息的权限,但没有设置权限
        cracker.setBalance(1);
        System.out.println(xiaowai.getAccount().getBalance());
        // 打印结果 xiaowai余额居然只有1块钱了
    }
}
​
class PeopleX{   
    // 用Account类作为自己的私有属性
    private Account account;
    private String name;
​
    public PeopleX( String name){
        this.name = name;
    }
    public void setAccount(Account account) {
        this.account = account;
    }
    public Account getAccount() {
        return account;
    }
​
}
​
class Account{
    private long balance;
    private long accountId;
​
    public Account(long balance,long accountId){
        this.balance = balance;
        this.accountId = accountId;
    }
    public Account(){}
    public void setBalance(long balance) {
        this.balance = balance;
    }
    public long getBalance() {
        return balance;
    }
}

 

 

产生结果

  • 破坏了类的封装性

  • 外部可以不通过set方法改变私有属性

 

产生原因

PeopleX提供了一个私有对象属性的引用,这里指的就是cracker

示意 图如下

原因了解了,那怎么解决呢?

 

解决方案

  • 在PeopleX类中返回Account新的对象,避免传引用对象

    1. public Account getAccount() {
              if(account != null)
                  return new Account(account.balance,account.accountId);
              else
                  return new Account();
          }
    2. 使用clone方法

      public Account getAccount() {
              return (Account) hireDay.cone();
          }

      这里的clone方法又有比较深的研究。

  • 这里还有一种情况有待考证,当Account属性中还有一个类对象属性,那该怎么返回Account对象更为合适呢?后续添加

posted @ 2020-04-27 13:04  随遇丿而安  阅读(184)  评论(0编辑  收藏  举报