如何通过使用from方法传递参数来为属性分配值?

问题描述 投票:0回答:2

我只需要使用一种设置方法就可以将YEAR,MONTH,DAY属性分配给值。因此,我通过逐行调用set方法,将DATE.YEAR,DATE.MONTH,DATE.DATE作为参数传递给参数。您可以对set方法进行任何更改。但是您不能更改主要方法。

   class Date{
    static int YEAR;
    static int MONTH;
    static int DAY;

    public void set(int field,int value){
        //i need to put code here to assign YEAR, MONTH, DAY to values
    }
    public void printDate(){
        System.out.println(YEAR+"-"+MONTH+"-"+DAY);
    }

}
class Demo{
    public static void main(String args[]){
        Date d1=new Date();
        d1.set(Date.YEAR,2016); //set(int field, int value)
        d1.set(Date.MONTH,05);
        d1.set(Date.DAY,30);
        d1.printDate(); //2016-5-30
    }
}
java object methods static arguments
2个回答
0
投票
class Date { static final int YEAR = 0; static final int MONTH = 1; static final int DAY = 2; private int year; private int month; private int day; public void set(int field, int value) { if (field == YEAR) this.year = value; else if (field == MONTH) this.month = value; else if (field == DAY) this.day = value; } public void printDate() { System.out.println(year + "-" + month + "-" + day); } }
© www.soinside.com 2019 - 2024. All rights reserved.