2015-10-27 48 views
2

我正在研究一個Java項目,其中有一個名爲Personnel的超類,以及兩個子類; ManagerWorkerJava - 無法從子類對象訪問抽象方法

子類包含用於保存有關他們的薪酬信息獨立變量,我以前有方法getSalary()ManagergetWage()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' 
} 

不太確定這裏發生了什麼問題,我想我已經覆蓋了需要完成的一切。正如你可以從我的代碼提取中看到的,該方法在超類中!

我真的不知道該從哪裏出發,任何推動正確的方向將不勝感激!

謝謝, 馬克

+0

@Cemre這是最肯定不正確。Java的沒有按沒有那個關鍵字,並且@ @ Override'註釋是可選的 – blagae

+0

在子類中嘗試使用@ @ Override,並且抽象方法'public'沒有意義,因爲抽象方法不能是'private'或'protected',並且在繼承時,您不能在子項中分配比從父項繼承的子項更弱的訪問權限。 –

+0

對不起,我在C#中編寫的代碼太久了:) – Cemre

回答

-1

當你做一個抽象類的方法,你是從這個「父」告訴JVM,「童車」將有那些方法,並且要麼執行它們,或者他們的「柴爾茲「執行它們。

Absctract類的方法不能在對象本身中使用對象細節,它們不能被實例化。

要麼getAnnualIncome()工人經理兩個(和他們的「孩子」),或具有抽象類做的方法。

爲了解決您的問題,使用註釋@Override,通知的Java 6+,代碼合法化(而可選的,這可能幫助),並檢查層次是正確的

2

您能夠創建將兩個子類中的對象作爲元素的Personnel類的數組? ,因爲它本身會給你錯誤。 「不能轉換的子類(工人/經理)人事[]。

在工作正常的你,比問題與註釋@Override情況。