Abstract class get parameter from implementing subclass?

Posted by soren.qvist on Stack Overflow See other posts from Stack Overflow or by soren.qvist
Published on 2012-09-23T09:35:40Z Indexed on 2012/09/23 9:37 UTC
Read the original article Hit count: 145

Filed under:

I'm wondering if there is way to do this without breaking encapsulation, I want the abstract class to rely on parameters defined in the implementing subclass. Like so:

public abstract class Parent {

    private int size;
    private List<String> someList;

    public Parent() {
        size = getSize();
        someList = new ArrayList<String>(size);
    }

    public abstract int getSize();

}

public class Child extends Parent {

    @Override
    public int getSize() {
        return 5;
    }

}

Is this ugly? Is there a better way? And perhaps more importantly, is this even a good idea?

© Stack Overflow or respective owner

Related posts about java