I have been reading up on Java and oop design. One of the exercises was to design a system to hold astronomical objects and some basic attributes of them.
the system needs to hold Stars, Galaxies and Planets.
Each Object has a type, eg for stars; dwarf, giant and normal
Starts also have a colour.
So far I started with a abstract base class for all these objects called AstronomicalObject:
public abstract class AstronomicalObject {
//Is this totally pointless?
}
I then made 3 classes Star, Galaxy and Planet that extend this class. For each type of these Objects I made additional subclasses ie DwarfStar that extends Star. Is this an acceptable idea? The additional classes feel slightly redundant:
public class DwarfStar extends Star{
public final String SIZE = "DWARF";
public DwarfStar(String colour) {
super(colour);
}
}
For the colour attributes I did this:
public class Star extends AstronomicalObject{
public final static String YELLOW = "YELLOW";
public final static String RED = "RED";
public final static String WHITE = "WHITE";
public final static String SIZE = "NORMAL";
private String colour;
public Star(String colour) {
this.colour = colour;
}
public String getColour(){
return this.colour;
}
}
So to create a star object I would use:
DwarfStar ds = new DwarfStar(Star.YELLOW);
Unfortunately the book doesn’t have an answers page or discuss this exercise so I was wondering if my solution was valid oop design. Or if it could be improved upon?
if your three objects have a
typeas you said, then no it isn’t useless as you will be able to write only one setter and getter in your superclass instead of implementing it in each subclass. In fact a superclass is not useless if every subclasses have a common property.Then for the colours you could use an Enum instead of static variables:
and access them with
Colours.REDfor example.