我正试图从另一个类中调用一个方法,但是从来没有教过我们如何正确地做到这一点。我需要在电影课中使用prodCompany来从生产课中获取生产信息,但是我不确定如何在我的电影课中返回带有多个变量的结果。
\\My movie class:
public void setProdCompany(String someName, String someCity, String someState) {
prodCompany = someName + someCity + someState;
}
public String toString() {
String result = "\nMovie Title:\t\t" + movieTitle + "\nMovie Length:\t\t"
+ length + "\nMovie Year:\t\t" + year + "\nMovie Production:\t" +
prodCompany + "\n\n";
return result;
}
\\From my production class:
public class Production {
private String companyName;
private String locationCity;
private String locationState;
public Production() {
companyName = "?";
locationCity = "?";
locationState = "?";
}
public String getCompanyName() {
return companyName;
}
public String getLocationCity() {
return locationCity;
}
public String getLocationState() {
return locationState;
}
public void setCompanyName(String someName) {
companyName = someName;
}
public void setLocationCity(String someCity) {
locationCity = someCity;
}
public void setLocationState(String someState) {
locationState = someState;
}
public String toString() {
String result = companyName + " at " + locationCity + " " +
locationState;
return result;
}
}
除此之外,一切正常,我的输出如下:
Choice Action
------ ------
A Add Movie
D Display Movie
Q Quit
? Display Help
What action would you like to perform? a
Please enter the Movie information:
Enter its title: Field of Dreams
Enter its length: 107
Enter its year: 1989
Enter its production company name: Gordon Company
Enter its production company's city: Thomasville
Enter its production company's state: NC
What action would you like to perform? D
Movie Title: Field of Dreams
Movie Length: 107
Movie Year: 1989
Movie Production: null
答案 0 :(得分:0)
您需要建立和理解什么是实际方法功能以及如何访问另一个类的基本逻辑。 让我们看看如何做到这一点:
public void getProdCompany() { //Check here, there is no point passing arguments.
Production prod = new Production(); // Calling your constructor and creating a Production instance.
// From your Production instance:prod , you may access the getters of Production's private variables.
prodCompany = prod.getCompanyName() + prod.getLocationCity() + prod.getLocationState();
}
答案 1 :(得分:0)
您不应将prodCompany
类中的Movie
设置为字符串,而应将其设置为Production
类型。
您似乎想用问号初始化生产公司。然后,您可以覆盖生产公司的名称,城市和州。因此,您的Movie
类应如下所示:
public class Movie {
private Production prodCompany;
public Movie() {
prodCompany = new Production();
}
public void setProdCompany(String someName, String someCity, String someState) {
prodCompany.setCompanyName(someName);
prodCompany.setLocationCity(someCity);
prodCompany.setLocationState(someState);
}
...
答案 2 :(得分:0)
在另一个类的调用之前,您需要实例化它。在您可以调用其方法之后。
赞:
private Production prodCompany = new Production();
public void setProdCompany(String someName, String someCity, String someState) {
prodCompany = someName + someCity + someState;