【问题标题】:using static variables as arguments in a method? [closed]在方法中使用静态变量作为参数? [关闭]
【发布时间】:2020-07-02 09:42:28
【问题描述】:

我是 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){
        //


            //
    }
}
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 。如何在 set 方法中编码。任何人都可以帮助我解决这个问题。非常感谢。

【问题讨论】:

  • 我不明白这个问题。你说“我被卡住了”,但从未描述过问题或错误。

标签: java oop methods static encapsulation


【解决方案1】:

如果我的问题正确,您应该首先将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);

【讨论】:

    猜你喜欢
    • 2021-07-03
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多