什么是“静态”意味着当声明“全局”变量在Java? [英] What exactly does "static" mean when declaring "global" variables in Java?

查看:107
本文介绍了什么是“静态”意味着当声明“全局”变量在Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直遇到这个问题很多次,我从来不想知道为什么它的发生和学习静态实际意味着什么。我只是应用了Eclipse建议和改变的改变。

I've been running into this problem many times and I never bothered to learn why its happening and learn what "static" actually means. I just applied the change that Eclipse suggested and moved on.

public class Member {

 // Global Variables
 int iNumVertices;
 int iNumEdges;

 public static void main(String[] args) {

  // do stuff

  iNumVertices = 0; // Cannot make a static reference to the non-static field iNumVertices

  // do more stuff

 } // main end 
}

因此eclipse让我做 static int iNumVertices; 不知道为什么。那么什么是静态,它是如何使用的,什么是使用静态的目的,为什么会给我这个问题?

So eclipse tells me to do static int iNumVertices; and I'm not sure why. So what exactly is "static", how is it used, what is the purpose of using "static", and why is it giving me this problem?

推荐答案

以下是您的示例:

public class Member {

    // Global Variables
    int iNumVertices;
    int iNumEdges;

    public static void main(String[] args) {

        // do stuff

        iNumVertices = 0; // Cannot make a static reference to the non-static field iNumVertices

    }
}

方法 main 是与类关联的静态方法。它不与 Member 的实例相关联,因此它无法访问与 Member 的实例相关联的变量。解决方案是不是使这些字段静态。相反,您需要使用 new 关键字创建 Member 的实例。

The method main is a static method associated with the class. It is not associated with an instance of Member, so it cannot access variables that are associated with an instance of Member. The solution to this is not to make those fields static. Instead, you need to create an instance of Member using the new keyword.

以下是修改版本:

public class Member {
    // Fields
    private int iNumVertices;
    private int iNumEdges;

    public Member(){
        // init the class
    }

    public static void main(String[] args) {
        Member member = new Member();
        member.iNumVertices = 0;
        // do more stuff
    }
}

创建全局静态是一个迹象,你应该仔细考虑你如何设计的东西。这不是总是错了,但它应该告诉你想想你在做什么。

Finding yourself creating global statics is an indication to you that you should think carefully about how you're designing something. It's not always wrong, but it should tell you to think about what you're doing.

这篇关于什么是“静态”意味着当声明“全局”变量在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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