为什么要以静态方式访问静态字段? [英] Why should the static field be accessed in a static way?

查看:199
本文介绍了为什么要以静态方式访问静态字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);

发出警告 - 静态字段MyUnits.MILLSECONDS应该以静态方式访问?
谢谢。

giving warnings-The static field MyUnits.MILLSECONDS should be accessed in a static way ? Thanks.

推荐答案

因为当您访问静态字段时,您应该在类上(或在此案例enum)。如在

Because when you access a static field, you should do so on the class (or in this case the enum). As in

MyUnits.MILLISECONDS;

不在实例上,如

m.MILLISECONDS;

修改解决为何的问题:在Java中,当您将某些内容声明为 static 时,您说它是类的成员,而不是对象(因此只有一个)。因此,在对象上访问它是没有意义的,因为该特定数据成员与该类关联。

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.

这篇关于为什么要以静态方式访问静态字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆