Potatosaurus Potatosaurus - 28 days ago 10
Java Question

Variable declared in abstract class not found in child implementation

Planning on having multiple classes extended from a super class, and for the sake of simplicity I've tried to declare common variables in the super class so I just need to assign them a value in the sub classes, however the child classes aren't recognising the variables.

Abstract class:

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


Example implementation:

@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:
...
}


As far as I can see, it look legal and it seems like it should work, but Netbeans just isn't recognising the variables.

Answer

Superclass variables are accesible from the superclass context only, meaning that the inherit variables will be directly accesible by referencing them with the reserved word "this". In order for this to work the superclass variable must be declared as public or protected

Notice that if you have a local variable inside your child class with the same name as your superclass variable then "this" will reference your local varaible, in order to use your superclass varaible in this case you'll have to use the reserved word "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

    ...
}

However I would not recommend you to access these varaibles directly, you could provide a Getter/Setter method and access them from those.