2016-11-10 77 views
0

計劃從一個超類擴展多個類,爲了簡單起見,我試圖在超類中聲明公共變量,所以我只需要爲它們分配一個值在子類中,但是子類不能識別變量。在子類實現中找不到的變量中聲明的變量

抽象類:

public abstract class AbstractAPIService { 
    public String APIDocumentation; //Selected API Documentation location 
} 

實現示例:

@Path("/Transport") 
@Stateless 
public class TransportAPI extends AbstractAPIService { 
    APIDocumentation = "http://docs.transportapi.com/index.html?raml=http://transportapi.com/v3/raml/transportapi.raml"; 

    //Desired Functionality: 
    ... 
} 

據我所看到的,它看起來法律和它看起來像它應該工作,但Netbeans的只是不承認變量。

回答

0

超類變量僅超背景下入店,這意味着繼承變量將用保留字「this」引用它們直接入店。爲了使這項工作超類變量必須聲明爲public or protected

請注意,如果你有你的子類中的局部變量具有相同的名稱爲您的超變量則「this」將引用您的本地varaible,爲了使用你的超varaible在這種情況下,你將不得不使用保留字「super

@Path("/Transport") 
@Stateless 
public class TransportAPI extends AbstractAPIService { 
    this.APIDocumentation = "http://docs.transportapi.com/index.html?raml=http://transportapi.com/v3/raml/transportapi.raml"; 

    //Desired Functionality: 

    //Access your superclass variable 
    String value = this.APIDocumentation; //or super.APIDocumentation 

    ... 
} 

但是我不建議你直接訪問這些varaibles,你可以提供一個getter/setter方法和訪問它們從那些。

0

錯誤的方法。你做不是使用一個簡單的變量。好的OO大約是行爲,而不是關於字段/變量。

你不喜歡這樣:

public abstract class Base { 
    protected abstract String getApiDocumentation(); 

    public final foo() { 
    String apiDoc = getApiDocumentation(); 

注意這裏:

  1. 我會繼續的東西,代表一些 「位置」 保護;含義:這是應該不是公衆。這聽起來像一些實施細節,這是你不暴露到外面的世界。另一方面,如果你有外部調用的方法,那麼你很可能想要阻止那個子類改變非抽象方法的行爲;因此經常適當宣佈這些最後的
+0

或者將字符串作爲參數傳遞給超級用戶,它具有在超類ctor中可用的優點(在構造函數中調用可覆蓋的方法時非常不恰當)。 –

+0

這迫使你擁有該構造函數。可能的,但不是(我的)首選解決方案。 – GhostCat