I have a class called Monster, every Monster has a name, dateofbirth, and a weapon. and The Monster constructor should have the following signature:
Monster(String name, int day, int month, int year, String weaponName)
To create a monster the following code should work:
new Monster("Godzilla",11,10,2000,"VenomThrower")
So I create the datafield in Monster:
public String name;
public MyDate dateOfBirth;
public int day;
public int month;
public int year;
public Weapon weapon;
However, I have to use the MyDate class defined below to create a MyDate object for dateofbirth. And use the Weapon class defined below to create a Weapon object for the monster’s weapon.
If I have to use the Object MyDate and Weapon, their type would be different from the constructor(int day, int month, int year) and (String weaponName), I try to cast the parameters, but it compiles error. Except casting, is there another way to achieve this?? Thank you.
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;
}
}
As you've seen, you can't just go and cast arbitrary variables to other classes. You could, however, call the respective constructors of MyDate
and Weapon
in Monster
's constructor:
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);
}
}