我是初学者,所以请非常具体。无论如何,我这里有三个代码类,我想从 c-b 然后 b-a 访问数据。
class GoobyPls {
{
private int CHealth = 20;
private int MHealth = 20;
private int CAgility = 10;
private int MAgility = 10;
private int CDefence = 5;
private int MDefence = 5;
}
}
class Stats {
public static void foo() {
string Health = CHealth + "/" + MHealth ;
string Agility = CAgility + "/" + MAgility;
string Defence = CDefence + "/" + MDefence;
}
}
class ViewStats {
public static void foo() {
System.out.println("Health");
System.out.println(Health);
System.out.println(" ");
System.out.println("Agility");
System.out.println(Agility);
System.out.println(" ");
System.out.println("Defence");
System.out.println(Defence);
System.out.println(" ");
}
}
所以 GoobyPls
是 a
,Stats
是 b
而 ViewStats
是 c
我也不能把它全部放在一个类中,因为最终会有一个修饰类来编辑 CHealth
、MHealth
等
最佳答案
在您的类 GoobyPls
中为每个项目添加 getter,如下所示:
class GoobyPls {
{
private int CHealth = 20;
public int getHealth(){
return Chealth;
}
}
然后在 viewStats
中执行此操作:
GoodyPls gp = new GoobyPls();
System.out.println(gp.getHealth());
当你想使用一个私有(private)变量时,只要调用 getters 即可。或者你也可以定义变量public,这样你就可以直接在viewStats中调用它们。但是从设计的角度来看,getter 和 setter 更好,因为隐藏信息更好。 应将字段声明为私有(private),除非有充分的理由不这样做。
关于java - 从其他类访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18271799/