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";
}
3
  • How are you calling the property? Commented Apr 12, 2012 at 13:11
  • Try to change the var value in the constructor Commented Apr 12, 2012 at 13:12
  • you may look at stackoverflow.com/questions/685300/… Commented Apr 12, 2012 at 13:21

2 Answers 2

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");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.