0

I have an Abstract class, which is derived by another Concrete class. In my abstract class I have a property which is called in method of the same Abstract class. This property is empty in Abstract class but in derived I set a value to it. Nevertheless, when compiler launches the method it takes abstract class' variable, not regarding that I'm launching this method on an Object of the derived class. How do I get the actual URL var instead of null ?

abstract public class AbstractHTTPFactory {
    protected String URL = null;

    final public ArrayList<? extends LGCookObject> make() throws HTTPFactoryException{
        try {
            String response = sr.getData(URL);
            }
    }
}

public class RecipesHTTPFactory extends AbstractHTTPFactory{
    protected String URL = "VALUE";
}
Carlos Gavidia-Calderon
  • 7,145
  • 9
  • 34
  • 59

2 Answers2

4

Fields aren't polymorphic. If you want polymorphic behaviour, you'll need methods:

public abstract class AbstractHTTPFactory {
    public final ArrayList<? extends LGCookObject> make()
            throws HTTPFactoryException {
        String response = sr.getData(getURL());
        ...
    }

    protected abstract String getURL();
}

public class RecipesHTTPFactory extends AbstractHTTPFactory {
    protected String getURL() {
        return "VALUE";
    }
}

Or potentially you could have a field in AbstractHTTPFactory which is supplied to the constructor:

public abstract class AbstractHTTPFactory {
    private final String url;

    public final ArrayList<? extends LGCookObject> make()
            throws HTTPFactoryException {
        String response = sr.getData(url);
        ...
    }

    protected AbstractHTTPFactory(String url) {
        this.url = url;
    }
}

public class RecipesHTTPFactory extends AbstractHTTPFactory {
    public RecipesHTTPFactory() {
        super("VALUE");
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

If you really want to keep the URL definition in your abstract base class, set it's value in the derived concrete class instead of redefine a variable with the same name which will hide the base class one. It's not a good practice though since there will be mysterious variables appear in derived class.

dragon66
  • 2,645
  • 2
  • 21
  • 43