将一个 class 的实例变量设置为另一个 class 的实例变量和
Setting the instance variables of one class to the instance variables of another class and
有没有办法将一个class的实例变量设置为另一个class的实例变量,当第二个class的实例变量发生变化时,实例第一个 class 的变量在用 class 制作对象之前也随之改变?这是我的狗 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);
}
}
这是我的猫class:
public class Cat {
int size = 5;
}
如您所见,我必须用它们制作对象才能将 dog.size 设置为 cat.size。有没有办法让它在你创建对象之前,Dog class 中的实例变量 'size' 自动设置为 Cat class 中的实例变量 'size' ]?基本上,如果 Cat class 中的实例变量 'size' 设置为 20,我希望我用 Dog class 制作的每个对象的实例变量 'size' 也得到设置为 20。我希望我的解释不会太混乱。哦,还有,我知道你可以通过继承来做到这一点,但我实际使用的 class 已经继承了另一个 class,所以我不能使用那个方法。如果有人知道任何其他方法,请告诉我。谢谢你。
我无法理解你的意思,但我想我知道你在说什么。
每次Cat's 'size' variable is changed, change every Dog's 'size' variable
。如果是这种情况,请使用列表存储您的 Cat
class 可以访问的所有 Dog
实例。
// from java.util package.
List<Dog> dogs = new ArrayList<>();
在您的 Cat
class 中,您需要一种方法来处理这两件事:
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.
}
另请注意,每次创建 Dog
时,您都需要将其添加到 dogs
列表中。
-或-
按照人们在评论中所说的,使用 static
成员,而不是 instance
成员。
有没有办法将一个class的实例变量设置为另一个class的实例变量,当第二个class的实例变量发生变化时,实例第一个 class 的变量在用 class 制作对象之前也随之改变?这是我的狗 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);
}
}
这是我的猫class:
public class Cat {
int size = 5;
}
如您所见,我必须用它们制作对象才能将 dog.size 设置为 cat.size。有没有办法让它在你创建对象之前,Dog class 中的实例变量 'size' 自动设置为 Cat class 中的实例变量 'size' ]?基本上,如果 Cat class 中的实例变量 'size' 设置为 20,我希望我用 Dog class 制作的每个对象的实例变量 'size' 也得到设置为 20。我希望我的解释不会太混乱。哦,还有,我知道你可以通过继承来做到这一点,但我实际使用的 class 已经继承了另一个 class,所以我不能使用那个方法。如果有人知道任何其他方法,请告诉我。谢谢你。
我无法理解你的意思,但我想我知道你在说什么。
每次Cat's 'size' variable is changed, change every Dog's 'size' variable
。如果是这种情况,请使用列表存储您的 Cat
class 可以访问的所有 Dog
实例。
// from java.util package.
List<Dog> dogs = new ArrayList<>();
在您的 Cat
class 中,您需要一种方法来处理这两件事:
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.
}
另请注意,每次创建 Dog
时,您都需要将其添加到 dogs
列表中。
-或-
按照人们在评论中所说的,使用 static
成员,而不是 instance
成员。