What exactly does “static” mean when declaring “gl

2020-04-04 05:42发布

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 
}

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?

8条回答
淡お忘
2楼-- · 2020-04-04 06:28
learn what "static" actually means

What static actually means that Class variable will be same for all instance of that particular class, however if you want to avoid using static variables(which is a good idea, since static variables are being kept in memory) you can pass variable value trough constructor thereby avoiding usage of static modifier, and achieve the same effect(that is if you pass the same value upon class instantiation).

Here is code example :

public class Car{

    private int speed;

    public Car(int speed){
        this.speed = speed;
    }

}

So you can do this when creating new instance :

Car car = new Car(100);

and every time you create Car instance it will have speed 100, thus avoiding static declaration private static int speed = 100;

查看更多
Summer. ? 凉城
3楼-- · 2020-04-04 06:28

Static variables do not need to have the class be instantiated in order to be accessed, so if you are trying to access a non-static variable form a static context you are risking trying to access something that has not been initialized/instantiated.

查看更多
登录 后发表回答