Santiago Benoit
Santiago Benoit

Reputation: 994

How to get the specific instance of a class from one of the instance variables that belong to it

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?

Upvotes: 1

Views: 123

Answers (4)

Alexander R&#252;hl
Alexander R&#252;hl

Reputation: 6939

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.

Upvotes: 1

M A
M A

Reputation: 72874

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);
   }
}

Upvotes: 3

atlanteh
atlanteh

Reputation: 5835

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;
    }
}

Upvotes: 0

KC-NH
KC-NH

Reputation: 748

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

Upvotes: 0

Related Questions