我试图调用BasicInfo类中的方法(全名(),alsoKnownAs())到另一个名为Customer的类中,特别是在displayInfo()部分,但不确定如何做到这一点,下面是我的代码:
enum Gender {MALE, FEMALE}
class BasicInfo
{
private String firstName, secondName, lastName;
private Gender g;
//Default Constructor
public BasicInfo()
{
//Do nothing
}
//Other Constructor
public BasicInfo(String firstName, String secondName, String lastName, Gender g)
{
this.firstName = firstName;
this.secondName = secondName;
this.lastName = lastName;
this.g = g;
}
//Copy Constructor
public BasicInfo(BasicInfo bi)
{
this.firstName = bi.firstName;
this.secondName = bi.secondName;
this.lastName = bi.lastName;
this.g = bi.g;
}
public String getFirstName()
{
return firstName;
}
public String getSecondName()
{
return secondName;
}
public String getLastName()
{
return lastName;
}
private Gender getGender()
{
return g;
}
public void setInfo(String firstName, String secondName, String lastName, Gender g)
{
this.firstName = firstName;
this.secondName = secondName;
this.lastName = lastName;
this.g = g;
}
private String fullName()
{
return (firstName + " " + secondName + " " + lastName);
}
private String alsoKnownAs()
{
return (firstName.charAt(0) + ". " + secondName.charAt(0) + ". " + lastName);
}
public void displayInfo()
{
System.out.printf("Full name: %s%n", fullName());
System.out.printf("Also known as: %s%n", alsoKnownAs());
System.out.printf("Gender: %s%n", getGender());
}
}
class Customer
{
private BasicInfo bi;
private int birthYear;
public Customer()
{
//Do nothing
}
public Customer(BasicInfo bi, int birthYear)
{
this.bi = bi;
this.birthYear = birthYear;
}
public Customer(Customer c)
{
this.bi = c.bi;
this.birthYear = c.birthYear;
}
public BasicInfo getBasicInfo()
{
return bi;
}
public int getBirthYear()
{
return birthYear;
}
public void setInfo(BasicInfo bi, int birthYear)
{
this.bi = bi;
this.birthYear = birthYear;
}
public void displayInfo()
{
System.out.printf("Full name: %s%n", bi.fullName());
System.out.printf("Also known as: %s%n", bi.alsoKnownAs());
System.out.printf("Gender: %s%n", bi.getGender());
System.out.printf("Year of birth: %d%n", birthYear);
}
}
在客户类displayInfo()中,我使用了“bi.fullName()”和“bi.alsoKnownAs()”和“bi.getGender()",这是方法调用的正确方式吗?如有任何帮助,我们将不胜感激:)
我也尝试使用“BasicInfo.'the method'",但仍然导致编译错误。
3条答案
按热度按时间fae0ux8s1#
这违反了Java的原则。如果一个方法被设计成在它的类之外被调用,那么它就不能是
private
。46scxncf2#
您应该将此方法的访问说明符更改为protected/public或default,因为只能在当前类中访问私有方法。
pdsfdshx3#
感谢大家花时间阅读我的帖子。
我将上面的内容改为:
它显示了BasicInfo类的displayInfo()方法的信息,也许我的问题一开始就不太清楚,我应该问如何从BasicInfo类调用displayInfo()方法到Customer类,而不是问如何访问私有方法。