对于这个问题,我得到了以下层次结构:基类Person,子类Employee和子类Staff和Supervisor。我需要在Employee,Staff和Supervisor类中应用方法覆盖。并且驱动程序类的主要方法需要创建Staff和Supervisor的多个对象,并显示其名称和月薪。
我在驱动程序类中构建了一个多态数组,但我无法弄清楚如何构造for循环以显示重写方法返回值旁边的数组的每个元素。我保持基础和子类非常简单:
public class Person {
void Salary(){
System.out.println("All positions are salaried");
}
}
public class Employee extends Person {
void Salary(){
System.out.println("Salaries vary between staff and supervisors");
}
}
public class Staff extends Employee {
public Staff(String string) {
}
void Salary() {
System.out.println("A regular staff employee makes 3500.00 monthly");
}
}
public class Supervisor extends Employee {
public Supervisor(String string) {
}
void Salary(){
System.out.println("Supervisors make approximately 9800.00 monthly");
}
}
这是驱动程序类,我遇到了问题:
import java.util.Arrays;
public class HRRoster {
public static void main(String[] args) {
Person roster[] = new Person[6];
roster[0] = new Supervisor("James Martin");
roster[1] = new Supervisor("William Smith");
roster[2] = new Supervisor("Jennifer Shipman");
roster[3] = new Staff("Brian Williams");
roster[4] = new Staff("Carrie James");
roster[5] = new Staff("Samantha Powers");
for (int i=0; i < roster.length; i++){
System.out.print(Arrays.toString(roster));
roster[i].Salary();
}
}
}
现在,它的输出是数组中的所有元素加上重写的方法,每个元素都在自己的行上。我知道我在for循环中遗漏了一些荒谬的基本/简单的东西,但我不确定如何让它从这里开始工作。基本上我想列出数组的每个元素,然后执行重写方法,每个元素都在自己的行上。
答案 0 :(得分:0)
你期待以下行为
import java.util.Arrays;
class Person {
String name;
void Salary() {
System.out.println("All positions are salaried");
}
public String toString(){
return name;
}
}
class Employee extends Person {
void Salary() {
System.out.println("Salaries vary between staff and supervisors");
}
public String toString(){
return name;
}
}
class Staff extends Employee {
public Staff(String name) {
this.name = name;
}
void Salary() {
System.out.println("A regular staff employee makes 3500.00 monthly");
}
public String toString(){
return name;
}
}
class Supervisor extends Employee {
public Supervisor(String name) {
this.name = name;
}
void Salary() {
System.out.println("Supervisors make approximately 9800.00 monthly");
}
public String toString(){
return name;
}
}
public class HRRoster {
public static void main(String[] args) {
Person roster[] = new Person[6];
roster[0] = new Supervisor("James Martin");
roster[1] = new Supervisor("William Smith");
roster[2] = new Supervisor("Jennifer Shipman");
roster[3] = new Staff("Brian Williams");
roster[4] = new Staff("Carrie James");
roster[5] = new Staff("Samantha Powers");
for (int i = 0; i < roster.length; i++) {
System.out.print(roster[i].toString() + "\t");
roster[i].Salary();
}
}
}