我出现的唯一错误是在该类中找不到getName()和getSalary()。我正在尝试获取输入到testEmployee类中的信息,以使用use Employees并显示结果。我收到一条Build Successful消息,但没有输出。
public abstract class Person {
// Variables
private String name;
private String ssn = null;
public Person(String name) {
this.name = name;
}
// Pass data to the object Person
/**
*
* @param ssn
*/
public void setSsn(String ssn) {
this.ssn = ssn;
}
public String getSsn() {
return ssn;
}
/**
*
* @return
*/
public abstract String getName();
}
class Employee extends Person {
// Variables
private String jobTitle;
private double salary;
private String getName;
private double cost;
public Employee(String name) {
super(name);
salary = 0;
jobTitle = null;
}
// Pass values to the obljects
// Setters
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public void setSalary(double cost) {
salary = cost;
}
// Getters
@Override
public String getName() {
return getName();
}
public String getTitle() {
return getJobTitle();
}
public double getSalary() {
return salary;
}
/**
* @return the jobTitle
*/
public String getJobTitle() {
return jobTitle;
}
/**
* @return the getName
*/
public String getGetName() {
return getName;
}
/**
* @param getName
* the getName to set
*/
public void setGetName(String getName) {
this.getName = getName;
}
/**
* @return the cost
*/
public double getCost() {
return cost;
}
/**
* @param cost
* the cost to set
*/
public void setCost(double cost) {
this.cost = cost;
}
}
public class testEmployee {
public static void main(String[] args) {
Employee emp1 = new Employee("John Smith");
String ssn = "333224444";
String jobTitle = "Web Designer";
double cost = 60000;
System.out.println("Employee " + getName() "n The current compensation is " + getSalary());
}
}
在main
的println
函数中,需要使用emp1.getName()
和emp1.getSalary()
而不是getName()
和getSalary()
调用getName
和getSalary
方法时,使用在main
方法中创建的Employee
emp1
的实例:
System.out.println
("Employee " + emp1.getName() + "n The current compensation is " + emp1.getSalary());
注意getName()
之后的附加+
操作员
这里还有一个StackOverflowError
场景,其中getName
递归地称自己为无限
@Override
public String getName() {
return getName();
}
由于name
是Person
的类成员变量,因此在中实现此方法
public String getName() {
return name;
}
这同样适用于Employee
中的getTitle
。更换
public String getTitle() {
return getJobTitle();
}
带有
public String getTitle() {
return jobTitle;
}