代码之家  ›  专栏  ›  技术社区  ›  Maciaz

原始对象是否会受此代码影响?[副本]

  •  -1
  • Maciaz  · 技术社区  · 6 年前

    我的一个朋友写了这样的代码:

    public AccountModel updateAccountPotential(Long accId) {
    
        AccountModel accModel = accountDAO.findById(accId);
    
        this.calculatePotential(accModel);
        return accountDAO.save(accModel);
    }
    
    private void calculatePotential(AccountModel accModel) {
        accModel.setPotential(some formula);
    }
    

    有这种方法 calculatePotential 它不返回任何内容,但对参数的字段执行一些操作。是否会影响中的原始对象 updateAccountPotential 方法?

    1 回复  |  直到 6 年前
        1
  •  1
  •   T.J. Crowder    6 年前

    是的,假设 setPotential 是一个典型的setter,因为 updateAccountPotential 是对对象的引用。该方法修改对象的状态(通过 定电位 )(大概)。就好像你这样做了:

    AccountModel a = /*...get the account model...*/;
    AccountModel b = a;
    b.setPotential(/*...*/);
    // Both `b` and `a` refer to the same object, and so the state of that object
    // is visible whether you go through `b` or `a` to get to it