我正在尝试使用另一个类中的add方法,以便我可以测试我的程序,但我仍然坚持如何继续。
在我的Apartment
课程中,我创建了一个添加方法
public void addApartment(Apartment newApartment)
{
House ApartmentEntry = new Apartment();
ApartmentEntry= newApartment;
ArrayList.add(ApartmentEntry);
}
在Company
课程中,我尝试使用上述方法添加Apartment
,如下例所示(在Company
中):
addApartment(price, numberofbaths, numberofbedrooms, squarefeet);
答案 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));