1

Can someone explain how the below code works without any exceptions. I am thinking when new instance is created for SUNDAY it creates a new instance for MONDAY (inside SUNDAY) too and then SUNDAY again (inside MONDAY) and so on... Something like recursive as they both are part of the class Week. But my understanding is wrong because the below code is working fine.

public class Week {
    public static final Week SUNDAY = new Week("SUNDAY",0);
    public static final Week MONDAY = new Week("MONDAY",1);

    private String name;
    private int val;

    private Week(String name, int val) {
        this.name = name;
        this.val = val;
    }

    public int getIndex() {
        return this.val;
    }

    @Override
    public String toString() {
        return this.name;
    }
}

I got this doubt when I was reading about java enums.

Dale K
  • 25,246
  • 15
  • 42
  • 71

2 Answers2

2

SUNDAY and MONDAY are static variables. Which means that they are class variables. Object of class Week will not have properties called SUNDAY and MONDAY

You can get more information regarding static here: What does the 'static' keyword do in a class?

Ivan
  • 8,508
  • 2
  • 19
  • 30
2

You will see the mentioned behavior when SUNDAY and MONDAY are instance variables (non-static).

Since you have declared them as static those are the properties of the class and initialized when the Week class is loaded one after another. One object creation SUNDAY would not contain MONDAY in it and vice versa.

As I mentioned in the beginning, the below code won't run successfully as it will try to create instances recursively without an end.

public class Week {

    public final Week SUNDAY = new Week("SUNDAY",0);
    public final Week MONDAY = new Week("MONDAY",1);

    private String name;
    private int val;

    private Week(String name, int val) {
        this.name = name;
        this.val = val;
    }

    public int getIndex() {
        return this.val;
    }

    @Override
    public String toString() {
        return this.name;
    }

    public static void main(String[] args) {
        new Week("TUESDAY", 2);
    }
}
fiveelements
  • 3,649
  • 1
  • 17
  • 16
  • `System.out.println(Week.SUNDAY.MONDAY)` is working fine because class variables can be accessed either by ClassName.staticVariable or classInstance.staticVariable ? – Lochan Pranay Aug 27 '19 at 19:48
  • Yes, when declared as `static`, these `class` variables can be accessed as `Class.variable` or `instance.variable` (no difference). However, you should access `static` variables as `Class.variable`. – fiveelements Aug 27 '19 at 19:52
  • Understood Thank You :) – Lochan Pranay Aug 27 '19 at 19:55