So let's say I have 2 classes, House
and Dog
I would like the Dog
to know about the House
it resides in, and vice versa.
I currently have these 2 classes setup:
House 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();
}
}
Dog class:
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;
}
}
Finally I have this main class to tie them both together:
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());
}
}
Console output:
Alex resides in 123 Main street
123 Main street has a dog named Alex
I would essentially like to know if there is a better way of having both of these classes exchange data/information between each other. I feel like what I have right now is likely very messy/sloppy, and probably not good design practice. Open for any feedback/advice.
Thanks