我用自己的私有變量編寫了我的類,然後編寫了訪問這些變量所需的訪問器和增量方法,但是在編寫主類之後運行它時,這不起作用。 ?爲什麼是發生在這裏查看我的代碼:我寫了Accessors和Mutators方法,但仍然無法訪問私有變量!爲什麼?
public class DateTest{
public static void main (String [] args){
Date d1 = new Date();
Date d2 = new Date();
d1.month = "February ";
d1.day = 13;
d1.year = 1991;
d2.month = "July";
d2.day = 26;
d2.year = 1990;
d1.WriteOutput();
d2.WriteOutput();
}
}
class Date {
private String month;
private int day;
private int year;
public String getMonth(){
return month;
}
public int getDay(){
return day;
}
public int getYear(){
return year; }
public void setMonth(String m){
if (month.length()>0)
month = m;
}
public void setDay(int d){
if (day>0)
day = d; }
public void setYear(int y){
if (year>0)
year = y;
}
public void WriteOutput(){
System.out.println("Month " + month + "Day "+ day + " year" + year);
}
}
請你們只是耐心和我在一起,我真的是一個「新手」程序員
好吧,我確實通過他們的設置方法調用了它們,實際上它也不起作用 – AbdullahR 2012-01-10 23:25:37
因爲,您永遠不允許更新字段 - 「if(month.length()> 0)」,我認爲您的意思是'if(m.length()> 0)'。這同樣適用於其他制定者。 – Krizz 2012-01-10 23:27:52
糟糕!是的,我相信那是我的錯誤。謝謝你! – AbdullahR 2012-01-10 23:37:14