public enum MyUnits { MILLSECONDS(1, "milliseconds"), SECONDS(2, "seconds"),MINUTES(3,"minutes"), HOURS(4, "hours"); private MyUnits(int quantity, String units) { this.quantity = quantity; this.units = units; } private int quantity; private String units; public String toString() { return (quantity + " " + units); } public static void main(String[] args) { for (MyUnits m : MyUnits.values()) { System.out.println(m.MILLSECONDS); System.out.println(m.SECONDS); System.out.println(m.MINUTES); System.out.println(m.HOURS); } } }
This is referring to post ..wasnt able to reply or comment to any so created a new one. Why are my
System.out.println(m.MILLSECONDS);
giving warnings-The static field MyUnits.MILLSECONDS should be accessed in a static way ? Thanks.
A static field or class variable is useful in certain programming languages and code situations to assign a particular variable (representing a common characteristic) to all instances of a class, either as a fixed value, or one that could change in the future.
A static method manipulates the static variables in a class. It belongs to the class instead of the class objects and can be invoked without using a class object. The static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded.
Advantages of Static Method in PHPIt allows many classes to access to the behavior that is not dependent on an instance of any static method. Grouping together stateless utility methods in a helper class makes it very clear of what's happening and creates a class that is cohesive and coherent.
Static methods are usually preferred when: All instance methods should share a specific piece of code (although you could still have an instance method for that). You want to call method without having to create an instance of that class. You must make sure that the utility class is never changed.
Because when you access a static field, you should do so on the class (or in this case the enum). As in
MyUnits.MILLISECONDS;
Not on an instance as in
m.MILLISECONDS;
Edit To address the question of why: In Java, when you declare something as static
, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With