Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should the static field be accessed in a static way?

Tags:

java

static

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.

like image 590
Ava Avatar asked Apr 12 '11 23:04

Ava


People also ask

What is the purpose of a static field?

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.

What's the purpose of static methods and static variables?

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.

What is the benefit of static method?

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.

When should you use a static method?

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.


1 Answers

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.

like image 88
Chris Thompson Avatar answered Sep 19 '22 17:09

Chris Thompson