[英]inheritance and constructors for the super class
当我在超类和子类之间放置一个箭头时,它会提示:没有找到合适的构造函数(对于超类对象。在这种情况下为 Person 中的 Date)。
构造函数和继承的故事是什么? 为什么超类需要子类中的构造函数?
这里是超类的构造函数:
public class Date
{
protected int _day;
protected int _month;
protected int _year;
public final int MAX_DAY = 31;
public final int MIN_DAY = 1;
public final int MAX_MONTH = 12;
public final int MIN_MONTH = 1;
public final int DEFUALT_YEAR = 4;
public Date (int day, int month, int year)
{
if( (MIN_DAY <= day) && (day <= MAX_DAY) && (MIN_MONTH <= month)
&& (month <= MAX_MONTH) && (year == DEFUALT_YEAR))
{
this._day = day;
this._month = month;
this._year = year;
}
else
{
this._day = 1;
this._month = 1;
this._year = 2000;
}
}
public Date (Date other)
{
_day = other._day;
_month = other._month;
_year = other._year;
}
这里是子类的构造函数:
public class Person extends Date
{
private String _first;
private String _last;
private long _id;
private Date _date;
public Person (String first, String last, long id, int d, int m, int y)
{
this._first = first;
this._last = last;
this._id = id;
Date _date = new Date(d, m, y);
}
public Person (Person other)
{
this._first = other._first;
this._last = other._last;
this._id = other._id;
this._date = other._date;
}
您需要调用super()
以使构造函数兼容例如。
public class Person extends Date
{
private String _first;
private String _last;
private long _id;
// private Date _date; Lose the Date as every property of date is accessible here
public Person (String first, String last, long id, int d, int m, int y)
{
super(d, m, y)
this._first = first;
this._last = last;
this._id = id;
}
public Person (Person other)
{
this._first = other._first;
this._last = other._last;
this._id = other._id;
this._day = other._day;
this._month = other._month;
this._year = other._year;
}
...
}
参考: https : //docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
参考: https : //docs.oracle.com/javase/tutorial/java/IandI/super.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.