为什么我需要实例化我的 class 才能在静态方法中调用我的方法?

Why do I need to make instantiate my class to call my method in the static method?

我开始学习 Java 并且有一个新问题。我的 class 块中有一组实例,其中包含 2 个方法、1 个主要静态和 1 个 void

public class CurrencyConverter {
    int rupee = 63;
    int dirham = 3;
    int real = 3;
    int chilean_peso = 595;
    int mexican_peso = 18;
    int _yen = 107;
    int $austrailian = 2;
    int dollar = 0;
    int Rupee = 63;

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
        // TODO code application logic here
        CurrencyConverter cc = new CurrencyConverter();
        cc.printCurrencies();
    }

    void printCurrencies() {
        System.out.println("rupee: " + rupee);
        System.out.println("dirham: " + dirham);
        System.out.println("real: " + real);
        System.out.println("chilean_peso: " + chilean_peso);
        System.out.println("mexican_peso: " + mexican_peso);
        System.out.println("yen: " + _yen);
        System.out.println("australian: " + $austrailian);
        System.out.println("dollar: " + dollar);
        System.out.println("Rupee: " + Rupee);                
    }       
}

现在我的问题是,为什么我需要实例化我的 CurrencyConverter class 才能调用 printCurrencies()?无论如何,您通常不能只调用方法吗?我在同一个 class 街区?

我尝试将 printCurrencies() 的访问修饰符更改为静态,但我的局部变量不是静态的

为什么我需要实例化?

将 class 视为对象的模式或配方。实例化时,您会创建一个具有此特定模式的对象。现在有一个具有您可以访问的值的对象。模式(所以 class)只有对可以保存特定值的字段的描述。因此没有您可以访问的值。

现在是静力学: 静态字段是在运行时开始时创建的字段。因此,您可以随时访问该值而无需创建对象,因为它们不属于对象而是属于特定的 class.

您摆脱实例化的解决方案是使 class 的所有成员成为静态的。

(记住:每个 const 成员都是静态的)

非静态字段与实例相关联。每个实例都有这些字段的一份副本。

public class CurrencyConverter {
    int rupee = 63; // non static instance field
    int dirham = 3; // non static instance field
    // etc.

why do I need to instantiate my CurrencyConverter class in order to call printCurrencies()?

没有实例,您的副本为零,因此没有可打印的内容。

Can't you normally just call methods anyway?

如果您将方法设为静态并删除对实例字段的所有引用,那么是的,您可以。这运行得很好,但它不再做任何有用的事情。

public static void main(String[] args) {
    printCurrencies();
}

static void printCurrencies() {
}  

I am in the same class block?

不太清楚你的意思,但是只有一个class,里面什么都有。

int rupee = 63;
int Rupee = 63;

除非你喜欢混淆,否则不要这样做。你应该在名称中明确每个字段的不同用途。

I tried changing the access modifier of printCurrencies() to static but then my local variables aren't static. Why do I NEED to instantiate?

非静态字段的副本在您明确创建它们之前不存在。