我是初学者,所以请非常具体。无论如何,我在这里有三个代码类,我想从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(" ");
  }
}


因此GoobyPlsaStatsbViewStatsc

我也不能将其全部放在一个类中,因为最终会有一个修饰符类来编辑CHealthMHealth

最佳答案

在您的课程GoobyPls中,为每个项目添加吸气剂,如下所示:

class GoobyPls {
{
   private int CHealth = 20;

   public int getHealth(){
      return Chealth;
   }
}


然后在viewStats中执行以下操作:

GoodyPls gp = new GoobyPls();
System.out.println(gp.getHealth());


只需在需要使用私有变量时调用getter。或者,您也可以定义变量public,以便您可以在viewStats中直接调用它们。但是从设计的角度来看,获取和设置更好,因为隐藏信息更好。
除非有充分的理由不这样做,否则应将字段声明为私有。

关于java - 从其他类访问数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18271799/

10-09 03:58