【问题标题】:Is it possible to declare a class object without passing down constructor parameters?是否可以在不传递构造函数参数的情况下声明类对象?
【发布时间】:2022-11-20 22:51:26
【问题描述】:

对于格式错误的问题,我深表歉意,但我处在一种奇怪的情况下,想不出解决方法。我基本上得到了一个文件,我从中读取数据并基于该数据创建类的实例。

List<HybCar> HybCar = new ArrayList<HybCar>();
List<GasCar> GasCar = new ArrayList<GasCar>();
List<ElCar> Elcar = new ArrayList<ElCar>();   

 while(sc2.hasNextLine()){
 //Some logic based on text file
 if( some condition )
  ElCar el = new ElCar(brand, model, engine_power, capacity, price);
  Elcar.add(el);
  else ( another condition )
  GasCar gas = new GasCar(brand, model, displacement, engine_power, price);
  GasCar.add(gas);
  //....etc.
  } // While loop ends.

通过这种方式,我在 while 循环中获得了类的实例,但我需要事先访问它们。由于它们的构造函数不为空,因此它们需要参数,但我只在 while 循环中获得了有关这些参数的信息,因为它们随着文本文件的每一行而变化。

那么在 while 循环之外访问这些类实例的最佳方法是什么,因为我稍后需要使用它们。我在 List 变量中获得了信息,但我不确定如何(以及是否应该)根据那里的信息创建类的新实例。

【问题讨论】:

    标签: java class oop constructor instance


    【解决方案1】:
         while(sc2.hasNextLine()){
      List parameters = getParametersFromLine();
         //Some logic based on text file
         if( some condition )
      ElCar el = new ElCar(parameters.get(0), parameters.get(1), parameters.get(2), parameters.get(3), parameters.get(4));
          Elcar.add(el);
          else ( another condition )
          GasCar gas = new GasCar(parameters.get(0), parameters.get(1), parameters.get(2), parameters.get(3), parameters.get(4));
          GasCar.add(gas);
          //....etc.
          } 
    

    是什么阻止你做类似上面的事情?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-22
      • 1970-01-01
      • 2010-10-10
      • 2012-02-10
      • 2011-12-04
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      相关资源
      最近更新 更多