Write a class SpaceBody for the space bodies (the Sun, Mercury, Venus, the Earth, the Moon,...). A SpaceBody should have a name, a center for its orbit and an identity number.
This class should look like the Employee class we studied.
Provide a constructor and accessors to the different fields.
Then write a class to test your SpaceBody class: enter several space bodies, and print out some of them.
Correction:
/**A Space Body (planets, stars, moons) has a name, a center for its orbit,
and an Id number. All Id numbers are different.
@author Thierry Coulbois
@date November, 12th, 2002
*/
class SpaceBody{
private String name; //All fields are private. As they should always be.
private SpaceBody orbitCenter;
private int idNumber;
private static int nextIdNumber=1; //A static field to calculate the idNumber of new SpaceBodies.
/**Constructor. We write only one constructor : you need to know the name and the orbitCenter
of a SpaceBody before creating it.
*/
public SpaceBody(String aName, SpaceBody aCenter){
name=aName;
orbitCenter=aCenter;
idNumber=nextIdNumber; //IdNumber is calculated according to nextIdNumber.
nextIdNumber++; //New value of nextIdNumber.
}
/**Accessor.*/
public String getName(){
return name;
}
/**Accessor.*/
public SpaceBody getOrbitCenter(){
return orbitCenter;
}
/**Accessor.*/
public int getIdNumber(){
return idNumber;
}
}
/**Test the SpaceBody class.
Create the sun, Mercury, Venus, The Earth and the Moon.
Printout some of the datas.
*/
class SpaceBodyTest{
public static void main(String[] args){
SpaceBody sun = new SpaceBody("The Sun",null);
SpaceBody mercury = new SpaceBody("Mercury",sun);
SpaceBody venus = new SpaceBody("Venus",sun);
SpaceBody earth = new SpaceBody("The Earth",sun);
SpaceBody moon = new SpaceBody("The Moon",earth);
System.out.println(moon.getName()+" ("+moon.getIdNumber()+") is orbiting around "
+moon.getOrbitCenter().getName()+".");
System.out.println(mercury.getName()+" ("+mercury.getIdNumber()
+") is orbiting around the space body of Id number: "
+mercury.getOrbitCenter().getIdNumber()+".");
}
}