Warning - Static Field Year Access

I use Calendarto access the current year.

This is my code ...

import java.util.Calendar;
Calendar c = c.getInstance();
int year = c.get(c.YEAR);

The code compiles and works fine, but it displays the warning message “Warning, access to static field”. Is something wrong, or should I do something better?

+3
source share
4 answers

Use Calendar.getInstance()and Calendar.YEAR, static fields should not be accessible using object instances.

+4
source

Calendar c = c.getInstance();Do it instead Calendar c = Calendar.getInstance();. The method getInstance()is a static class method Calendar, so you get a warning.

ADD

The same applies to Calendar.YEAR

+1
source

, , , .

:

public class AAA{
    public static String HELLO = "HI";
}
public class BBB extends AAA{
    public static String HELLO = "Hello World";
}

AAA test = new BBB();
System.out.println(test.HELLO); //Will print String from AAA 
                                //instead of "Hello World"

static "Hello World".

To prevent these errors, you should always refer to the static variables in the class in which they are declared, instead of using an instance. The compiler warns you because there is no reason not to use the class name.

+1
source

Of course, it is advisable to change your code. However, if you just want to avoid changes, use the method annotation: @SuppressWarnings ("static access")

0
source

Source: https://habr.com/ru/post/1785491/


All Articles