开发者

Warning - Accessing Static Field Year

开发者 https://www.devze.com 2023-02-04 14:59 出处:网络
I am using a Calendar to gain access to the current year. This is my code... import java.util.Calendar;

I am using a Calendar to gain access to the current year.

This is my code...

import java.util.Calendar;
Calendar c = c.getInstance()开发者_如何学JAVA;
int year = c.get(c.YEAR);

The code compiles and runs fine, but it displays a warning message saying "Warning, accessing a static field" Is there something wrong, or should I be doing something better?


Use Calendar.getInstance() and Calendar.YEAR, static fields should not be accessed using instance objects.


Instead of doing Calendar c = c.getInstance(); , do this Calendar c = Calendar.getInstance();. The getInstance() method is a static method of Calendar class and that is why you are getting the warning.

ADD

The same goes for Calendar.YEAR


It warns you because static fields are accessed using the compile time type and not the runtime type of the object, which can cause hard to find bugs.

Example:

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"

Without the static it will print "Hello World".

To prevent these bugs you should always access static variables by the class they are declared in instead of using an instance. The compiler warns you since there is no good reason not to use the class-name.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消