【问题标题】:How do I use a add method for another class如何为另一个类使用 add 方法
【发布时间】:2014-12-15 10:54:35
【问题描述】:

我正在尝试使用另一个类中的 add 方法,以便我可以测试我的程序,但我不知道如何继续。

在我的 Apartment 类中,我创建了一个 add 方法

public void addApartment(Apartment newApartment)
{
   House ApartmentEntry = new Apartment();
   ApartmentEntry= newApartment;
   ArrayList.add(ApartmentEntry);
}

Company 类中,我尝试使用上述方法添加Apartment,如下例所示(在Company 中):

addApartment(price, numberofbaths, numberofbedrooms, squarefeet);

【问题讨论】:

  • 这个问题很混乱。你能说的更清楚吗
  • 你的命名约定也很混乱。
  • 我真的不明白你的问题,但你为什么要创建一个公寓的新实例,然后立即用方法参数覆盖它?您是要创建对象的副本并将其保存在列表中还是什么?

标签: java class inheritance arraylist


【解决方案1】:

由于你的addApartment 方法不是静态的,你必须创建一个Company to use it. Plus, you don't have anaddApartmentmethod taking several parameters, so I guess you wanted to use those for the constructor ofApartment` 的实例:

Company company = new Company(args);
company.addApartment(new Apartment(price, numberofbaths, numberofbedrooms, squarefeet));

【讨论】:

    【解决方案2】:

    好吧,假设你有一个带有这样的构造器的 Apartment 类:

    public class Apartment{
    
        public Apartment(int price, int numberOfBaths, int numberOfBedrooms, int squarefeet){
             this.price = prive;
             ...
        }
    }
    

    这就是您创建新公寓实例的方式:

    Apartment newApartment = new Apartment(price, numberOfBaths, numberOfBedrooms, squarefeet);
    

    知道了,您的 addApartment 方法可能看起来像这样:

    public void addApartment(int price, int numberOfBaths, int numberOfBedrooms, int squarefeet)
    {
       House ApartmentEntry = new Apartment(price, numberOfBaths, numberOfBedrooms, squarefeet);
       ...
    }
    

    我不知道你想用那个 ArrayList 做什么,但你肯定要先声明它:

    ArrayList<Apartment> list = new ArrayList<Apartment>();
    list.add(newApartment);
    

    【讨论】:

      【解决方案3】:

      在我看来,您正在尝试将Apartment 添加到Company

      Company 类应该有 addApartment(...) 方法。

      所以Company 类会是这样的:

          public class Company{
              private ArrayList<Apartment> apartments;
      
              public Company(){
                  apartments = new ArrayList<Apartment>();
              }
      
              public addApartment(Apartment apartment){
                  this.apartments.add(apartment);
              }
          }
      

      那么你会:

      Company company = new Company(args...);
      company.addApartment(new Apartment(price, numberOfBaths, numberOfBedrooms, squarefeet));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-05
        • 2019-03-11
        • 1970-01-01
        • 2011-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多