【发布时间】:2016-11-15 04:17:28
【问题描述】:
抽象类 Java 为什么我的程序只打印 0.00?
public class TestEmployee
{
public static void main(String[] args)
{
Employee[] folks = new Employee[4];
folks[0] = new SalariedEmployee("Suzy",123,520000.00);
folks[1] = new WageEmployee("Fred",456,7.50,40);
folks[2] = new SalariedEmployee("Harry",234,45000.00);
folks[3] = new WageEmployee("Rita",345,7.76,38);
for(int i=0; i<folks.length; i++)
{
System.out.println(folks[i].getName()
+ " earns " + folks[i].getMonthlyPay() + " each month");
}
}
}
我添加了制作所需的缺失类 程序编译运行正常
abstract class Employee
{
private String name;
private int number;
public abstract double getMonthlyPay();
public Employee(String name, int number, double salary)
{
setName(name);
setNumber(number);
salary = getMonthlyPay();
}
public Employee(String name, int number, double salary, int hours)
{
setName(name);
setNumber(number);
salary = getMonthlyPay();
}
public String getName()
{
return this.name;
}
public int getNumber()
{
return this.number;
}
public String setName(String name)
{
this.name = name;
return this.name;
}
public int setNumber(int number)
{
this.number = number;
return this.number;
}
}
请解释或了解我的程序为何只打印零。我想这就是我的问题所在
class SalariedEmployee extends Employee
{
private double yearSalary;
public SalariedEmployee(String name, int number, double salary)
{
super(name, number, salary);
yearSalary = getMonthlyPay();
}
public double getMonthlyPay()
{
double monthlyPay = yearSalary / 12;
return monthlyPay;
}
public String toString()
{
return(super.getName() + ", " + super.getNumber() + ", " + getMonthlyPay());
}
}
class WageEmployee extends Employee
{
private double wage;
private int hours;
public WageEmployee(String name, int number, double salary, int hours)
{
super(name, number, salary, hours);
}
public double getMonthlyPay()
{
double monthlyPay = wage * hours * 4;
return monthlyPay;
}
public String toString()
{
return(super.getName() + ", " + super.getNumber() + ", " + getMonthlyPay());
}
}
【问题讨论】:
-
这是学习使用调试器和使用此工具帮助您首先识别然后解决错误的最佳时机。附带说明一下,在将代码发布到此站点或任何站点以寻求帮助时,您应该努力将其格式化,以便人们能够阅读它。这包括为您的代码提供适当且常规的缩进。
-
public WageEmployee(String name, int number, double salary, int hours)...我在父类Employee中没有看到兼容的定义构造函数。 -
你设置
yearSalary = getMonthlyPay()和getMonthlyPay()被定义为monthlyPay = yearSalary / 12。那么年薪取决于月薪,而月薪取决于年薪?这已经没有任何意义了。另外,我看不到您在哪里初始化yearSalary变量。 -
Chit,你正在为构造函数中的参数赋值——不要那样做。寻找重复的来关闭它。
-
您认为
Employee构造函数的double salary参数在做什么,您为什么这么认为?您认为构造函数结束时参数的值存储在哪里,为什么会这样认为?
标签: java abstract-class