I have a Parent.java class and 4 child classes as Child1.java, Child2.java and so on.
There are two methods
and one field
Field f1 has different values based on the child class.
Method m1 has the common implementation so I have put it in Parent.java class. It also refers method m2.
Method m2 has common implemtation but it process field f1 which is different for all the child classes.
So my questions are as follows:
Q1. Should I place the field f1 in the parent class and let all the child classes inherit them and initialize them in their own constructors or Should I make a field f1 for all the child classes.
Q2. As the method m2 has common implementation but process field f1 which doesn't have same value for every child class, so should I place it in parent class or child class.
Q3. If I should place the method m2 in parent class, the there is one problem that method m1 (which have common implementation) refer method m2, so would it create any problem?
Place m2 and f1 in the parent class if m2's implementation is the same for all classes. If there's a specific part for each child class that can be run after the common part - separate it and place it in the child classes while calling super.m2(). Set f1 in each child class's constructor.
The result will look something like this:
public abstract class parent {
private int field = 0;
public parent(int f) {
field = f;
}
public void m1() { /* m1's implementation */ }
public void m2() { /* m2's common implementation */ }
}
public class child1 {
public child1() {
super(1);
}
@Override
public void m2() { super.m2() /* m2's child1 implementation */ }
}
public class child2 {
public child2() {
super(2);
}
@Override
public void m2() { super.m2() /* m2's child2 implementation */ }
}
This should allow you to push the maximum amount of code as far back in the hierarchy as it can go. Least code duplication.
Edited to fix trying to access a private member from a child class. Changed to setting it using the constructor.
In my opinion:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With