在方法中使用静态变量作为参数?

问题描述 投票:-1回答:1

我是Java的新手。这些天,我正在处理OOP概念。我被困在这里是因为我无法决定如何在名为set的方法中编写代码来完成我的代码。这是我的代码

class Date {
    private int year=1970;
    private int month=1;
    private int day=1;
    static int YEAR;
    static int MONTH;
    static int DAY;

    public void setYear(int year){
        this.year=year;
    }
    public void setMonth(int month){
        this.month=month;
    }
    public void setDay(int day){
        this.day=day;
    }

    public void printDate(){
        System.out.println(year+"-"+month+"-"+day);
    }
    public void set(int field, int value){
        //
        field=value;
        this.year=YEAR;
        this.month=MONTH;
        this.day=DAY;
    }
}
class Demo{
    public static void main(String args[]){
        Date d1=new Date();
        d1.printDate();
        d1.set(Date.YEAR,2018);
        d1.set(Date.MONTH,04);
        d1.set(Date.DAY,18);
        d1.printDate();
    }
}

我坚持使用set method,有人可以帮我解决这个问题吗?非常感谢。

java oop methods static encapsulation
1个回答
0
投票

如果我正确地解决了该问题,则应首先将YEARMONTHDAY移至DateUnit枚举。

public enum DateUnit {
    YEAR, MONTH, DAY
}

然后使set方法接受DateUnit unitint value

public void set(DateUnit unit, int value) {
    switch (unit) {
        case YEAR: {
            year = value;
            break;
        }
        case MONTH: {
            month = value;
            break;
        }
        case DAY: {
            day = value;
            break;
        }
    }
}

现在您可以像这样使用它:

Date date = new Date();
date.set(DateUnit.YEAR,2018);
date.set(DateUnit.MONTH,04);
date.set(DateUnit.DAY,18);
© www.soinside.com 2019 - 2024. All rights reserved.