Alex Rivera | Logout

Using superclass "protected final" methods to keep common code for subclasses

Asked 2011-10-04T17:26:36.417
11

As a (pedantic) beginner Java programmer I would like to know, is it a good practice to move a common block of code that all subclasses use to a separate protected (final) method in parent class? Tasks like filling lists with common values, or common filtering algorithms, etc... Is it good to also use protected static methods?

class A {
    protected final List<String> getVariants() {...}
    protected final List<String> filterResults(List<String> variants) {...}
}

class B extends A {
    public List<String> doSomethingUsefull() {
        List<String> commonVariants = getVariants();
        ...
        return filterResults(commonVariants);
    }
}

class C extends A {
    public void doSomethingUsefull() {
        List<String> commonVariants = getVariants();
        ...
        return filterResults(commonVariants);
    }

    public void doMoreUsefullThings() {
        List<String> commonVariants = getVariants();
        ...
        return filterResults(commonVariants);
    }
}
Edit
Report

2 Answers

4

It seems reasonable to me - although you might want to make A abstract as well. Also consider using composition instead - could B and C contain an A instead of subclassing it?

answered 2011-10-04T17:29:24.197
0

I'd propose to move all this methods to separate static class if they don't depend on some class fields. Make them util methods.

answered 2011-10-04T17:30:10.643

Your Answer