2016-08-11 25 views
2

覆蓋抽象方法在抽象類中,我有以下定義:使用海格爲了功能的Java

protected abstract A expectedA(B b); 

    protected Function<A, B> createExpectedA(Long foo) { 
    return a -> { ... return b}} 

然後我想從createExpectedA覆蓋與返回功能的抽象功能,像這樣:

@Override 
    protected Function<A, B> expectedA = createExpectedA(fee); 

但是這給了我以下錯誤:

The annotation @Override is disallowed for this location

我該如何做到我想在Java8中實現的目標?

+0

你知道「正常」的方式來使用@覆蓋? –

+0

「受保護的抽象A expectedA(B b)」的返回類型與'protected Function expectedA = createExpectedA(fee)'的返回類型不匹配。從解決這個問題開始。 – bradimus

回答

3

註釋Override旨在用於不在字段上的方法,這就是爲什麼你會得到這個錯誤。作爲提醒,這裏的Javadoc:

Indicates that a method declaration is intended to override a method declaration in a supertype. If a method is annotated with this annotation type compilers are required to generate an error message unless at least one of the following conditions hold:

  • The method does override or implement a method declared in a supertype.
  • The method has a signature that is override-equivalent to that of any public method declared in Object.

你想要做什麼似乎是這樣的:

@Override 
protected A expectedA(B b) { 
    return createExpectedA(fee).apply(b); 
}