简体   繁体   English

为什么我需要在这里使用静态? 在这种情况下,我似乎不需要它

[英]Why do I need to use static here? It doesn't seem like I'd need it in this case

I've just recently picked up Java. 我最近才学Java。 This is my first day of coding. 这是我编码的第一天。 I have two classes. 我有两节课。 One is a class that gets user input and outputs it, and another is a class with its own methods and variables. 一个是获取用户输入并输出用户输入的类,另一个是具有自己的方法和变量的类。

CLASS 1: 第1类:

public class Player {
    // this is my player class
    private static int health;

    public void setHealth(int healthToSet) {
        health = healthToSet;
    }

    public static int getHealth() {
        return health;
    }
}

CLASS 2: 第2类:

import java.util.Scanner;

public class Obtainer {
    public static void main(String[] args) {
        System.out.println("Enter a number you'd like to set your health    to...");
        Scanner userInput = new Scanner(System.in);
        int givenInt = userInput.nextInt();

        Player newPlayer = new Player();

        newPlayer.setHealth(givenInt);

        int newHealth = Player.getHealth();

        System.out.println("OK, you have set your health to " +       newHealth);

        userInput.close();
    }

}

Eclipse prompted me to add a static modifier my getHealth method. Eclipse提示我在getHealth方法中添加一个静态修饰符。 I didn't need to do this with setHealth, after doing private int health; 在执行私有int健康之后,我不需要使用setHealth进行此操作; instead of private int health = 100;. 而不是private int health = 100;。 I know it says static, but that's after I added the static modifier to that and getHealth after I was prompted to. 我知道它说的是静态的,但是那是在提示我将static修饰符添加到getHealth之后的。 What is the point of this? 这有什么意义呢? What is the difference between getHealth and setHealth aside from the fact that setHealth returns no value and getHealth returns a value? 除了setHealth不返回任何值和getHealth返回一个值的事实之外,getHealth和setHealth有什么区别? Is that what's making me need to use a static modifier? 那是什么让我需要使用静态修饰符?

You should change int newHealth = Player.getHealth(); 您应该更改int newHealth = Player.getHealth(); to int newHealth = newPlayer.getHealth(); int newHealth = newPlayer.getHealth();

Since you are currently invoking the method on a class and not an object, the method has to be static, therefore the compiler complains if it is not. 由于您当前是在类而不是对象上调用方法,因此该方法必须是静态的,因此编译器会抱怨是否不是静态方法。

Yes, in this case I would not use static variables or method, so I would change to 是的,在这种情况下,我不会使用静态变量或方法,因此我将更改为

private int health;

public int getHealth() {...}

int newHealth = newPlayer.getHealth();

You can not access the instance methods with the class name. 您不能使用类名称访问实例方法。

Option 1 : newPlayer.getHealth(); 选项1: newPlayer.getHealth();

Option 2 : add the static modifier to getHealth() if it needs to access by Class name. 选项2:如果需要按类名访问,则将静态修饰符添加到getHealth()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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