简体   繁体   中英

What does the 'Static' keyword do?

I have a program where there are two shapes Player1 and Player2, both inherited by the class Player.

Public class Player{

    public int xPos;
    public int yPos;

    // more code

}

The player1 class:

Public class Player1 extends Player{

    public Player(){
        xPos = 200;
        yPos = 200;
    }
    // more code
}

The Player2 class:

Public class Player2 extends Player{

    public Player2(){

        xPos = 400;
        yPos = 200;
    }
// more code
}

In this case, should I use static for the xPos and yPos in the Player class?

不能。静态变量是类的成员,您希望位置变量成为对象的成员(非静态)。

如果xPos和yPos是静态的,则Player的每个实例将具有相同的位置。

The static keyword in front of a variable signifies that the variable in question belongs to the "class itself" as opposed to individual instances. In other words changing it with one instance changes it with all of them. So in this case, you should not do what you are asking.

No,

static as a keyword in Java means that the field is a Class field not a instance field. These are supposed to be used for fields that are used between instances of the class and don't have any meaning for a given instance. In your case the xPos and yPos are for each instance of the class.

Take a look at this static tutorial

The short answer is no .

A static variable or method means that no instance of this object is required to make use of it (for example, we don't create a new instance of class System when we do System.out.println ). It also means that the state of the object is consistent every time we call it; that is to say, if we set some value inside of a class with a static field, that value will stay consistent throughout all instances of that class.

Every x and y position is unique with respect to each instance of your Player object. You don't want to use static .

You use static when you want the values to be same in all its references. In your case i guess you want the xPos and yPos to be different for different players. In other words for each object you create for the class Player you want xPos and yPos to be different. So you don't declare them as static.

Additional Info: If you declare some variable as static, the method that uses it should be declared as static too.

No. Don't use static attributes in this case because xPos and yPos are attributes (properties) of each Player. Each Player that is created (instance) must have its own x and y.

The static keyword is used to create something that belongs to the class and not to the instance of the class.

For example, if xPos was static you could call Player.xPos to get the value of xPos, without the need to have an instance of the class, and all Players would have the same xPos and yPos.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM