我正在研究一個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