Reputation: 43
I have a class where I made an array of the planets.
private final static Planet[]
{
new Planet("Mercury"),
new Planet("Venus"),
new Planet("Earth"),
new Planet("Mars"),
new Planet("Jupiter"),
new Planet("Saturn"),
new Planet("Uranus"),
new Planet("Neptune")
};
and I need to retrieve it into another class.
public float getPlanetMass()
{
}
How exactly would I go about this?
Upvotes: 2
Views: 37
Reputation: 2808
You can have a public method in a class to return the planets and another class that will call that method to get the list. Something like below :
public class Test {
private Planet[] getPlanets(){
Planet[] planets = new Planet[8];
int index = 0;
for(String name : Arrays.asList("Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune")) {
planets[index++] = new Planet(name);
}
return planets;
}
static class PlanetClient{
public static void main(String args[]) {
Test test = new Test();
Planet[] planets = test.getPlanets();
System.out.println("Planets are " + Arrays.toString(planets));
}
}
class Planet {
String name;
Planet(String name){
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
}
Upvotes: 1
Reputation: 5246
There are a lot of ways to do this but instead of creating an array you could create an Enum
called Planet
or even an enum called StandardPlanet
or TerrestialPlanet
that implements an interface called Plant
. This way the enum uses the multiton pattern, you can reference these elements publicly, and you're not creating non-private mutable objects.
public interface Planet {
}
public enum TerrestialPlanet implements Plant {
EARTH,
MARS,
// etc
}
Planet planet = TerrestialPlanet.EARTH;
Upvotes: 0