gpt4 book ai didi

java - 如何在类外定义全局变量?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:16:03 26 4
gpt4 key购买 nike

我想定义可以与类共享值的变量。

所以我尝试如下。

但是它发生了错误。

如何向类共享一个值?

package com.company;

/////// Error occurred ///////
int sharedValue = 100; // <- How to share to classes?
//////////////////////////////

public class Main {

public static void main(String[] args) {
sharedValue += 10;

GlobalTest globalTest = new GlobalTest();
globalTest.printGlobalValue();
}
}

class GlobalTest {
void printGlobalValue() {
System.out.println(sharedValue);
}
}

最佳答案

您可以在您的类中将其声明为静态值:

public class Main {
public static int sharedValue = 100;
....
}

并使用以下方法从其他类访问它:

Main.sharedValue

关于java - 如何在类外定义全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20256541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com