[英]Setting the instance variables of one class to the instance variables of another class and
有没有一种方法可以将一个类的实例变量设置为另一类的实例变量,并且当第二个类的实例变量更改时,第一个类的实例变量也随之更改,然后再使对象脱离这两个类? 这是我的狗班:
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);
}
}
这是我的猫课:
public class Cat {
int size = 5;
}
如您所见,我必须将它们都做成对象才能将dog.size设置为cat.size。 有没有一种方法可以使您在创建对象之前,将Dog类中的实例变量“ size”自动设置为Cat类中的实例变量“ size”? 基本上,如果Cat类中的实例变量'size'设置为20,我希望我从Dog类中制作的每个对象的实例变量'size'也都设置为20。我希望我的解释不是太混乱。 哦,而且,我知道您可以通过继承来做到这一点,但是我实际上使用的类已经在继承另一个类,因此我不能使用该方法。 如果有人知道其他方法,请告诉我。 谢谢。
我很难理解您的意思,但我想我知道您在说什么。
每次Cat's 'size' variable is changed, change every Dog's 'size' variable
。 如果是这种情况,请使用列表存储Cat
类可以访问的所有Dog
实例。
// from java.util package.
List<Dog> dogs = new ArrayList<>();
在Cat
类中,您需要一个方法来处理这两种情况:
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
List中。
-要么-
遵循人们在评论中所说的话,并使用static
成员而不是instance
成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.