Java - 使其他类成为必需的类

时间:2016-06-20 08:04:39

标签: java

我有2级,星球和月球,我的计划是让月球类需要星球类,所以首先我创造星球然后创造月球,怎么做? 我的星球类:

public class planet {
    //planet name
    private String namaPlanet;
    //total moon per planet
    private int jmlBulan;
    //revolution and rotation
    private double jmlRotasi, jmlRevolusi;
public planet(String namaPlanet, int jmlBulan, double jmlJamPhari, double jmlHariPtahun) {
    this.namaPlanet = namaPlanet;
    this.jmlBulan = jmlBulan;
    this.jmlRotasi = jmlJamPhari;
    this.jmlRevolusi = jmlHariPtahun;
}

public planet(String namaPlanet, double jmlRotasi, double jmlRevolusi) {
    this.namaPlanet = namaPlanet;
    this.jmlRotasi = jmlRotasi;
    this.jmlRevolusi = jmlRevolusi;
}
}

月亮课:

public class bulan extends planet {
private String namaBulan;
public bulan(String namaBulan, String namaPlanet,double jmlJamPhari, double jmlHariPtahun) {
    super(namaPlanet, jmlJamPhari, jmlHariPtahun);
    this.namaBulan = namaBulan;
}
}

1 个答案:

答案 0 :(得分:1)

由于月亮不是一颗行星,你不应该从星球上获得你的月球类,而应该给月球一个行星的参考和/或让行星有一个卫星列表。

public class Moon {
    private String name;
    private Planet planet;

    public Moon(String name, Planet planet) {
         this.name = name;
         this.planet = planet;
    }
}