Skip to content

How to assign values to Attributes by passing argument using from method?

I need to assign YEAR, MONTH, DAY attributes to values just only using one set method. therefore I pass DATE.YEAR, DATE.MONTH, DATE.DATE as an argument also with values by calling set method line by line. You can make changes anything to the set method. But You cannot make changes to the main method.

   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(){

class Demo{
    public static void main(String args[]){
        Date d1=new Date();
        d1.set(Date.YEAR,2016); //set(int field, int value)
        d1.printDate(); //2016-5-30



Mark YEAR, MONTH AND DAY as final and use them in comparison in set() method

    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)
       = value;

        public void printDate() {
            System.out.println(year + "-" + month + "-" + day);
7 People found this is helpful