Let's say I have multiple instances of this class:
public class Star {
public Star(ArrayList<Planet> planets, ArrayList<Comet> comets) {
pla = planets;
com = comets;
}
// Getters and setters go here
private ArrayList<Planet> pla;
private ArrayList<Comet> com;
}
How can I work with the instance of Star
that, say, a specific Planet
belongs to? For example, see this pseudocode:
aSpecificPlanet.getInstanceOfClassThisBelongsTo().doStuffWithIt();
I've tried this in one of Planet
's getters:
public Star getStar() {
return this.getClass();
}
But I am getting this error: incompatible types: Class<CAP#1> cannot be converted to Star
How can I do this?
You're getting a Class
instance and not a Star
instance.
You can add a field in Planet
of type Star
which would reference the Star
to which it belongs. Whenever you add a Planet
to a Star
, this field can be set:
Star star = new Star(planets, comets);
for(Planet planet : planets) {
planet.setStar(star); // add this field
}
You can place this inside a utility method to avoid duplicating code and to ensure consistency:
public void addPlanet(Star star, Planet planet) {
if(star != null && planet != null) {
star.getPlanets().add(planet); // assuming the list is always not null
planet.setStar(star);
}
}
Misread the question - so here's a better answer:
What you are looking for is the typical use case of an 1:n relation in relational databases - you have 1 star having n planets and each of the planets belong to 1 star. In the database you'd model this with a foreign key in each table.
In Java, you could map it the same way (which you actually do when trying to model this relation via JPA): The star contains a list of all planets and the planet has a field containing the star.
You really cant'. As shown, there is no association from planet to star.
You may wish to review your class hierarchy. You current have Star with a 'has-a' relationship to Planet and Comet. Isn't it really the galaxy that contains all 3? Or maybe you want Planet to have 'has-a' relationship to Star
You need to have a reference to the star inside your planet. you can't get the instance without it.
public class Planet {
private Star star;
public void setStar(Star star)
{
this.star = star;
}
public Star getStar()
{
return this.star;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.