访问子类中的私有Int

时间:2012-03-22 23:34:53

标签: inheritance subclass private

超类源代码

public class Date {
private int month; 
private int day; 
private int year; 


public Date() {
setMonth(1);
**day = 1;**
setYear(1900);
}

public Date(int month, int day, int year) {
this.setMonth(month);
this.**day** = day;
this.setYear(year);
}

月和年工作正常,因为我可以在我的子类中使用setMonth和setYear。但是,当我尝试使用白天时,它表示var是不可见的,因为它是私有的。在超类中没有一天的setter,但是有一个吸气剂。二传手应该是什么样的?此外,我的子类构造函数应该是什么样的?

子类构造函数

public EDate(int month, int day, int year) 
{

this.setMonth(month);
day = getDay();
this.setYear(year);
}

Subclass Day setter

public void setDay(int newInt) {
if (isGooddDate(getMonth(), newInt, getYear())==true)
{    
newInt = this.getDay();
}

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

我认为不需要首先将Date类子类化。原因是因为无论发生什么,日期功能都将保持不变。所以不需要子类构造函数。

就日期制定者而言,你正朝着正确的方向前进:

public void setDate(int dateValue) {
    if(isDateValid(dateValue)) {
        date = dateValue;
    } else {
        throw new Exception("Invalid date");
    }
}

如果您的课程有时间支持,您实际上可以编写更好的解决方案。无论日期是什么,都要及时转换日期值。存储时,将时间转换为适当的日期。这就是内置DateTime类的工作原理。

例如:如果你存储2006-16-80,它将被存储为2007-06-19,而不是抛出异常。只是一个想法!