我正在研究一个Java项目,其中有一个名为Personnel
的超类,以及两个子类; Manager
和Worker
。Java - 无法从子类对象访问抽象方法
子类包含用于保存有关他们的薪酬信息独立变量,我以前有方法getSalary()
为Manager
和getWage()
为Worker
。不过,我想其中的一些可访问通过一个for循环,所以我把一个抽象方法到名为getAnnualIncome()
的Personnel
类,并把相应的方法到两个子类:
public abstract class Personnel
{
//attributes of each instance of class
protected String name;
protected int payrollNum;
protected String dept;
//abstract method to be defined in subclasses
public abstract float getAnnualIncome();
}
在Manager
:
public float getAnnualIncome()
{
//convert salary variable to real number
float salaryAsFloat = salary;
//return real number
return salaryAsFloat;
}
在Worker
:
public float getAnnualIncome()
{
//number of weeks in a year as constant value
final int weeksInYear = 52;
//weekly wage by number of weeks in a year
return ((hourlyRate * hoursPerWeek) * weeksInYear);
}
这一切工作正常的理论,但是当我来到居然小鬼(我使用Personnel
类的数组和两个子类的对象作为元素),下面的一段代码没有识别出getAnnualIncome()
方法(这取自可执行主类):
for (int index = 0; index < employee.length; ++index)
{
System.out.printf(employee[index].getName()
+ "\t\t" + "£%.2f %n", employee[index].getAnnualIncome());
//error message appears here ^^ 'method is undefined in 'Personnel'
}
不太确定这里发生了什么问题,我想我已经覆盖了需要完成的一切。正如你可以从我的代码提取中看到的,该方法在超类中!
我真的不知道该从哪里出发,任何推动正确的方向将不胜感激!
谢谢, 马克
@Cemre这是最肯定不正确。Java的没有按没有那个关键字,并且@ @ Override'注释是可选的 – blagae
在子类中尝试使用@ @ Override,并且抽象方法'public'没有意义,因为抽象方法不能是'private'或'protected',并且在继承时,您不能在子项中分配比从父项继承的子项更弱的访问权限。 –
对不起,我在C#中编写的代码太久了:) – Cemre