gpt4 book ai didi

Java公共(public)变量多个类

转载 作者:行者123 更新时间:2023-12-01 23:40:26 26 4
gpt4 key购买 nike

我很好奇公共(public)变量实际上是做什么的。我假设它们适用于包内的所有类,但显然情况并非如此。我想知道如何将 ADD 和 MULT 变量从第一类转移到第二类。这是我在第一个类上的代码:

    public class first {
public static int ADD = 0;
public static int MULT = 1;
public static int derp(int x, int x2, int a){
int septor = 0;
if(a == 0){
septor = x + x2;
}
if(a == 1 ){
septor = x * x2;
}
return septor;
}
}

第二课:

public class second {
public static void main(String args[]){
int y = first.derp(6,10,ADD);
System.out.println(y);
}
}

最佳答案

一如既往,您能做的最好的事情就是引用 docs :

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

Class variables are referenced by the class name itself

那里有一个很好的例子,按照它,你就会知道你应该写 first.ADD

也请关注Java Naming Convention并将 first 替换为 First

关于Java公共(public)变量多个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18036958/

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