Put m2 and f1 in the parent class if the implementation of m2 is the same for all classes. If there is a specific part for each child class that can be run after the common part, separate it and place it in the child classes when super.m2 () is called. Set f1 in each constructor of the child class.
The result will look something like this:
public abstract class parent { private int field = 0; public parent(int f) { field = f; } public void m1() { } public void m2() { } } public class child1 { public child1() { super(1); } @Override public void m2() { super.m2() } } public class child2 { public child2() { super(2); } @Override public void m2() { super.m2() } }
This should allow you to push the maximum amount of code back in the hierarchy as it can go. Less code duplication.
Edited to fix an attempt to access a private member from a child class. Changed to install it using the constructor.
source share