I can't find a solution to this inheritance problem. I'm working on a program which will store information about celestial bodies. I have an abstract superclass, Body
, from which all other celestial bodies should inherit. Now, I want some bodies to have implementation by default for storing information about orbiting bodies; some bodies should be Orbitable
and some should be Orbital
. e.g. a Star is orbitable
only, a Planets and Moons are both orbitable
and orbital
, and an Asteroid is orbital
only.
public abstract class Orbital {
Body host;
protected double avgOrbitalRadius;
protected double orbitalPeriod;
public double getOrbitalRadius(){return this.avgOrbitalRadius;}
public double getOrbitalPeriod(){return this.orbitalPeriod;}
}
public abstract class Orbitable {
List<Body> satellites = new ArrayList<>();
public void addSatellite(Body sat){
satellites.add(sat);
}
public boolean hasSatellite(Body sat){
for(Body body : satellites){
if(sat.equals(body)) return true;
}
return false;
}
public boolean hasSatellite(String satName){
for(Body body : satellites){
if(satName.equals(body.getName())) return true;
}
return false;
}
public Body getSatellite(String satName){
for(Body body : satellites){
if(satName.equals(body.getName())) return body;
}
return null;
}
}
I need to have objects be able to inherit one, both, or neither of the above implementations (plus the Body
superclass which describes the foundation for any celestial body).
I've tried using interfaces with default methods but the key problem is that the implementation involves reading or modifying the object's state, which cannot be implemented with interfaces because all variables in an interface are implicitly static.
I've also viewed this and this post about very similar issues, but the inheritance of state is causing me grief.
So, how can I solve this multiple inheritance problem? Is it even possible in Java? Are there other designs that could circumvent this problem? Thanks.