加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何在Java中“反驳”一个对象

发布时间:2020-12-15 05:00:32 所属栏目:Java 来源:网络整理
导读:class DogOwner { Dog dog; DogOwner(Dog dog) { this.dog = dog; }}class Dog { int age; Dog(int age) { this.age = age; }}DogOwner peter = new DogOwner(new Dog(2));Dog max = peter.dog;max.age = 3;System.out.println(peter.dog.age); // 3 我怎样
class DogOwner {
    Dog dog;

    DogOwner(Dog dog) {
        this.dog = dog;
    }
}

class Dog {
    int age;

    Dog(int age) {
        this.age = age;
    }
}

DogOwner peter = new DogOwner(new Dog(2));
Dog max = peter.dog;
max.age = 3;

System.out.println(peter.dog.age); // 3

我怎样才能最大限度地从彼得那里获得最大值,而不是最大限度地提及彼得所拥有的狗?换句话说,我希望能够将max的年龄设置为3而不改变peter的Dog.

解决方法

您必须克隆peter.dog,或者基于它创建新实例.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读