如何为另一个类使用add方法

时间:2014-10-20 12:41:32

标签: java class inheritance arraylist

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

在我的Apartment课程中,我创建了一个添加方法

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

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

addApartment(price, numberofbaths, numberofbedrooms, squarefeet);

3 个答案:

答案 0 :(得分:1)

由于您的addApartment方法不是静态的,因此您必须创建Company to use it. Plus, you don't have an addApartment method taking several parameters, so I guess you wanted to use those for the constructor of公寓的实例:

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

答案 1 :(得分:1)

好吧,假设你有一个带有这样的构造函数的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);

答案 2 :(得分:1)

在我看来,您正试图将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));