How to “refute” an object in Java

class DogOwner {
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

How can I get the maximum from Peter instead of mentioning Peter's dog? In other words, I want to be able to set Max's age to 3 without changing Peter's dog

Solution

You must clone Peter Dog, or create a new instance based on it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>