gpt4 book ai didi

java - 让类(class)相互交换信息的最佳方式?

转载 作者:太空宇宙 更新时间:2023-11-04 10:37:19 32 4
gpt4 key购买 nike

假设我有 2 个类,HouseDog

我希望了解它所居住的房子,反之亦然。

我目前有这两个类(class)设置:

<小时/>

房屋类别:

public class House {

private String address;
private Dog dog;

public House(String address, Dog dog) {
setAddress(address);
setDog(dog);
dog.setHouse(this);
}

public void setDog(Dog dog) {
this.dog = dog;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getDog() {
return dog.getName();
}

}

狗类:

public class Dog {

private House house;
private String name;

public Dog(String name) {
setName(name);
}

public void setHouse(House house) {
this.house = house;
}

public String getHouse() {
return house.getAddress();
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}
<小时/>

最后我有这个主类将它们连接在一起:

public class Main {

public static void main(String[] args) {

Dog dog = new Dog("Alex");
House house = new House("123 Main street", dog);

System.out.println(dog.getName() + " resides in " + dog.getHouse());
System.out.println(house.getAddress() + " has a dog named " + house.getDog());

}

}

控制台输出:

Alex resides in 123 Main street
123 Main street has a dog named Alex
<小时/>

我本质上想知道是否有更好的方法让这两个类在彼此之间交换数据/信息。我觉得我现在所拥有的可能非常困惑/草率,并且可能不是良好的设计实践。欢迎任何反馈/建议。

谢谢

最佳答案

我想你要找的东西在 this: Managing Bidirectional Associations in my Java Model 中这个问题恰好有其他有用的堆栈溢出答案的链接。

关于java - 让类(class)相互交换信息的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49333635/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com