是否可以像在 JS 中一样访问对象的变量。
例如:
import java.util.*;
class Dice{
public String [] side;
public String name;
public Dice (String n, String ... a){
name = n;
side = a;
}
//Setter and Getter side
public String getSide(){
return side;
}
public void setSide(String s){
side = n;
}
}
数组在 main 中初始化,如下所示:
Dice easy = new Dice("绿色:","大脑","大脑","大脑","脚印","脚印","猎枪");
它的名字是“绿色”。
其余的字符串对象存储在字符串数组中。
要在 JS 中访问数组,您可以:
Dice.side[1];
我们可以像这样在 Java 中访问它们吗?我正在尝试访问 main() 中的数组?
String theStringInArray = Dice.side[1];
System.out.println(theStringInArray);
在此示例中,结果应打印“Brain”。
(这仅供我自己引用,为了获得练习,我一直在阅读有关 ArrayList 的内容,但在此示例中仅使用数组:)
最佳答案
Dice easy = new Dice("Green:","Brain","Brain","Brain","Foot Print","Foot Print","Shotgun");
String theStringInArray = easy.side[1]; // getting the value through instance (easy)
System.out.println(theStringInArray);
如果你确实想像Dice.side[1]
那样访问;你必须使 side
数组成为静态变量。
public static String [] side;
关于java - 我可以像在 JS 中一样访问类构造函数变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57926233/