2

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.

3
  • 1
    Why not have the size in the class that they both inherit? Making it a static variable will do the trick. Commented Apr 4, 2015 at 20:08
  • @ZiadHalabi Dog is only inheriting one class, Cat. And making the instance variable static makes it so that you can't making objects of that that variable. Commented Apr 4, 2015 at 20:10
  • Yea that's what I meant! Commented Apr 4, 2015 at 20:12

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.