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?
EDIT:
The classes are created in the context of a framework, so the default parameter-less constructor is always the one called (in fact, the Parent class extends another class). The size parameter is just used for illustration purposes and I don’t plan on using it for a List implementation.
No, is not ugly. This pattern is named “template method”. But typically it is more useful when the method is not a simple getter but something that implement business logic.
In your case other solution is to define protected constructor in Parent class and call it with relevant parameter from child: