简体   繁体   中英

Setting the instance variables of one class to the instance variables of another class and

Is there a way to set the instance variables of one class to the instance variables of another class, and when the instance variables of the second class changes, the instance variables of the first class also change along with it BEFORE making objects out of either classes? This is my Dog class:

public class Dog {
int size;

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

public static void main(String args[]) {
    Cat cat = new Cat();
    Dog dog = new Dog(cat.size);

    System.out.println(dog.size);

    cat.size = 17;
    dog.size = cat.size;

    System.out.println(dog.size);

}

} 

This is my Cat class:

public class Cat {
int size = 5;

}

As you can see, I have to make objects out of both of them to set dog.size to cat.size. Is there a way to make it so that before you make the objects, the instance variable 'size' in the Dog class automatically gets set to the instance variable 'size' in the Cat class? Basically, if the instance variable 'size' in the Cat class gets set to 20, I want the instance variable 'size' of every object I make out of Dog class to also get set to 20. I hope my explanation wasn't too confusing. Oh, and also, I know you can do this with inheritance, but the class I'm actually using is already inheriting another class, so I can't use that method. If anyone know any other methods, please let me know. Thank you.

I'm having trouble understanding what you mean, but I think I know what you're saying.

Every time the Cat's 'size' variable is changed, change every Dog's 'size' variable . If that's the case, use a list to store all of your Dog instances that your Cat class can access.

// from java.util package.
List<Dog> dogs = new ArrayList<>();

In your Cat class, you'll need a method to handle both things:

public void setSize(int size) {
    // Set cat's size to size,

    // Get your java.util.List of dogs,
    // loop through them, and set each of their
    // size to the new size as well.
}

Also, note that each time you create a Dog , you'll need to add it to your dogs List.

-Or-

Go by what people are saying in the comments, and use a static member, instead of an instance member.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM