在子实现中找不到在抽象类中声明的变量

时间:2016-11-10 16:30:39

标签: java

计划从超类扩展多个类,为了简单起见,我试图在超类中声明公共变量,所以我只需要在子类中为它们赋值,但是子类没有认识到变量。

抽象类:

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只是没有认识到变量。

2 个答案:

答案 0 :(得分:0)

错误的做法。你做使用一个简单的变量。好的OO是关于行为,而不是关于字段/变量。

你这样做:

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

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

请注意:

  1. 我会保留代表某些“位置”受保护的内容;意思是:这应该公开。这听起来像是一些实现细节,而且你不会暴露到外面的世界。
  2. 另一方面,如果您有外部调用的方法,那么您很可能希望阻止该子类更改非抽象方法的行为;因此,宣布那些 final
  3. 通常是合适的

答案 1 :(得分:0)

超类变量只能从超类上下文访问,这意味着继承变量可以通过使用保留字“this”引用它们来直接访问。为了使其工作,必须将超类变量声明为public or protected

请注意,如果您的子类中有一个与您的超类变量同名的局部变量,那么“this”将引用您的本地变量,以便在这种情况下使用您的超类变量必须使用保留字“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

    ...
}

但是我不建议您直接访问这些变量,您可以提供Getter / Setter方法并从中访问它们。

相关问题