有没有一种方法可以将文件加载到Java中的多个类而不必每次都调用它们?

时间:2019-04-24 07:33:57

标签: java

我一直在为多层停车场编写程序,我必须将3个单独的文件装入停车场的空间,服务员和每个区域的成本。问题是我需要跨多个类访问它们,而不必每次都调用.load()方法。这导致程序无法正常运行,因为它重置了该类中的加载数据,因为我有两个主要的类Application和Admin需要在它们之间共享此数据。我该怎么做才能解决此问题?

其中包含公共静态void main的顶级类

var varray=new Array(); 
for (var i = 0; i < Page_Validators.length; i++)
 {
   if(!Page_Validators[i].isvalid)
    {
      varray.push(Page_Validators[i])
    }
 }
 console.log(varray);

从Application类调用该类

public class Application {

    private Scanner scan;
    private Admin admin;
    private ZoneCost zoneCost;
    private Attendants attendants;
    private Database database;

    private Application() {
        scan = new Scanner(System.in);
        admin = new Admin();
        zoneCost = new ZoneCost();
        attendants = new Attendants();
        database = new Database();
        zoneCost.load();
        database.load();
    }

如所见,两个类最终都调用相同的.load()方法

编辑感谢大家帮助我尽快解决了这个问题,它为我节省了大量时间!

1 个答案:

答案 0 :(得分:2)

只需使用构造函数将对象作为参数传递

public class Application {

        private Scanner scan;
        private Admin admin;
        private ZoneCost zoneCost;
        private Attendants attendants;
        private Database database;

        private Application() {
            scan = new Scanner(System.in);
            zoneCost = new ZoneCost();
            attendants = new Attendants();
            database = new Database();
            zoneCost.load();
            database.load();
            admin = new Admin(scan, zoneCost, database, attendants );
        }



    public class Admin {

        private Scanner scan;
        private Attendants attendant;
        private ZoneCost zoneCost;
        private Database database;

        Admin(Scanner scan, ZoneCost zoneCost, Database database, 
              Attendants attendant) {
            this.scan = scan;
            this.attendant = attendant;
            this.zoneCost = zoneCost;
            this.database = database;
        }