コンストラクタは、データフィールドと異なるパラメータの型を持っています

新ゆう呉:

私はすべてのモンスターは名前、dateOfBirthの、そして武器を持って、モンスターと呼ばれるクラスを持っています。そしてモンスターのコンストラクタは、次のシグネチャを持つ必要があります。

Monster(String name, int day, int month, int year, String weaponName)

次のコードは動作するはずのモンスターを作成するには:

new Monster("Godzilla",11,10,2000,"VenomThrower")

モンスターにデータフィールドを作成し、私はそう:

public String name;
public MyDate dateOfBirth;
public int day;
public int month;
public int year;
public Weapon weapon;

しかし、私はdateOfBirthのためMyDateに該当オブジェクトを作成するために、以下のように定義MyDateに該当クラスを使用する必要があります。そしてモンスターの武器のための武器オブジェクトを作成するには、以下の定義された武器クラスを使用します。

私は、オブジェクトMyDateに該当し、武器を使用する必要がある場合、そのタイプは、コンストラクタ(int型日、int型月、int型の年)と(文字列weaponName)とは異なるだろう、私はパラメータをキャストしようとするが、それはエラーをコンパイルします。鋳造を除き、これを達成するための別の方法があります?ありがとうございました。

public class MyDate {

    private int year;
    private int month;
    private int day;


    MyDate(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }
}

public class Weapon {

    private String name;
    Weapon(String n) {
        this.name = n;
    }
    public String getName()   {
        return name;
    }
}
Mureinik:

あなたが見てきたように、あなただけに行くと、他のクラスに任意の変数をキャストすることはできません。ただし、それぞれのコンストラクタを呼び出すことができMyDateそしてWeaponMonsterのコンストラクタを:

public class Monster {
    private String name;
    private MyDate dateOfBirth;
    private Weapon weapon;

    public Monster(String name, int day, int month, int year, String weaponName) {
       this.name = name;
       this.dateOfBirth = new MyDate(year, month, day);
       this.weapon = new Weapon(weaponName);
    }
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=232646&siteId=1