我正在关注Java for Dummies的书,我遇到了一个问题。我无法弄清楚为什么@Override不起作用。我确定它与我的代码有关,因为我之前已经有了一个多态数组来处理覆盖,但对我来说它太模糊了。
import static java.lang.System.out;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class DoPayrollTypeP {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner diskScanner = new Scanner(new File("EmpInfoNew.txt"));
Scanner kbdScanner = new Scanner (System.in);
for(int empNum = 1; empNum<=3; empNum++){
payOneFTEmployee (diskScanner);
}
for(int empNum = 4; empNum<=6; empNum++){
payOnePTEmployee(diskScanner, kbdScanner);
}
}
public static void payOneFTEmployee(Scanner diskScanner){
FullTimeEmployee ftemployee = new FullTimeEmployee();
ftemployee.setName(diskScanner.nextLine());
ftemployee.setJobTitle(diskScanner.nextLine());
ftemployee.setWeeklySalary(diskScanner.nextDouble());
ftemployee.setBenefitDeduction(diskScanner.nextDouble());
diskScanner.nextLine();
diskScanner.nextLine();
ftemployee.cutCheck(ftemployee.findPaymentAmount());
out.println();
}
public static void payOnePTEmployee(Scanner diskScanner, Scanner kbdScanner) {
PartTimeEmployee ptemployee = new PartTimeEmployee();
ptemployee.setName(diskScanner.nextLine());
ptemployee.setJobTitle(diskScanner.nextLine());
ptemployee.setHourlyRate(diskScanner.nextDouble());
diskScanner.nextLine();
diskScanner.nextLine(); //Reads the dashed line that
// separates two employees
out.print("Enter ");
out.print(ptemployee.getName());
out.print("'s hours worked this week: ");
int hours = kbdScanner.nextInt();
ptemployee.cutCheck(ptemployee.findPaymentAmount(hours));
out.println();
}
}
下一课:
import static java.lang.System.out;
public class Employee {
private String name;
private String jobTitle;
public void setName(String nameIn) {
name = nameIn;
}
public String getName() {
return name;
}
public void setJobTitle(String jobTitleIn) {
jobTitle = jobTitleIn;
}
public String getJobTitle() {
return jobTitle;
}
public void cutCheck(double amountPaid){
out.printf("Pay to the order of %s", name);
out.printf("(%s) ***$", jobTitle);
out.printf("%,.2f\n", amountPaid);
}
}
下一课:
public class PartTimeEmployee extends Employee{
private double hourlyRate;
public void setHourlyRate(double hourlyRateIn) {
hourlyRate = hourlyRateIn;
}
public double getHourlyRate() {
return hourlyRate;
}
public double findPaymentAmount(int hours){
return hourlyRate * hours;
} //method that should be overriden
}
应该覆盖的类:
public class PartTimeWithOver extends PartTimeEmployee{
@Override
public double findPaymentAmount(int hours) {
if(hours <= 40) {
return getHourlyRate() * hours;
} else {
return getHourlyRate() * 40 +
getHourlyRate() * 2 * (hours - 40);
}
}
}
EmpInfoNew。(txt)文件
jo shmo CEO 5000.00答案 0 :(得分:2)
您已将对象实例化为
base
这是PartTimeWithOther
overridden
类,因此无法在derived
课程中调用PartTimeEmployee ptemployee = new PartTimeWithOver();
方法。
更改为
sknode
here是一个很好的教程,附图解释多态性
答案 1 :(得分:0)
您永远不会使用PartTimeWithOver,您只能使用PartTimeEmployee。
因此永远不会调用您的overriden方法。