I'm trying to use simple inheritance to populate a varable depending on the status code of an API response but I'm having a weird error while saving the class.

The error message: Variable does not exist: preview

PreviewResponse response;
if (apiResponse.getStatusCode() == 200) {
    response = new SuccessfulPreviewResponse();
    response.isSuccess = true;
    response.preview = (ContentPreview) JSON.deserialize(apiResponse.getBody(), ContentPreview.class);
} else {
    response = new ErrorResponse();
    response.isSuccess = false;
    response.description = 'error';

And this is my class structure:

public class ContentPreview {
    public ContentPreviewData data;

public class ContentPreviewData {
    public String encoded_content;
    public String encoded_content_hash;
    public Decimal encoded_content_timestamp;
    public String img;

public virtual class PreviewResponse {
    public Boolean isSuccess { get; set; }

public class SuccessfulPreviewResponse extends PreviewResponse {
    public ContentPreview preview { get; set; }

public class ErrorResponse extends PreviewResponse {
    public String description { get; set; }

Unless I'm not understanding something about Apex inheritance I'm not sure what's the issue here since the "preview" variable is an attribute of "SuccessfulPreviewResponse", my intention here is to return this value to a lightning component and render the error response or the api call body.

Any help would be appreciated!


Since it's a subclass, you need to cast it to the appropriate type. Base classes don't know about their children's attributes. For example:

((SuccessfulPreviewResponse)response).preview = 
    (ContentPreview) JSON.deserialize(apiResponse.getBody(), ContentPreview.class);

Alternatively, I'd assign the value to the response variable after setting its attributes:

SuccessfulPreviewResponse successValue = new SuccessfulPreviewResponse();
successValue.preview = (ContentPreview) JSON.deserialize(apiResponse.getBody(), ContentPreview.class);
successValue.isSuccess = true;
response = successValue;
  • Many thanks! That worked flawlessly. I completely forgot about that "detail". :p – binomialheap Dec 7 '15 at 18:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.