Reputation: 377
I have an Interface I1
, one Abstract Class A1
which implements I1
and a lot of Classes C1
...n
which extend A1
.
Now, one class C3
is implementing a special behaviour for a Method methodA
of I1
, where every other extending Class of A1
is implementing a kind of default behaviour.
public interface I1 {
public void methodA();
}
public abstract class A1 implements I1 {
public void methodA(){
//default behaviour
}
//other methods
}
public class C1 extends A1 {
//do nothing regarding methodA, because the default behaviour is desired
//other methods
}
public class C2 extends A1 {
//do nothing regarding methodA, because the default behaviour is desired
//other methods
}
public class C3 extends A1 {
public void methodA(){
//special behaviour
}
//other methods
}
Now, for me, this does not seem like the best possible solution, since it is difficult to find out, that C3
is overriding some method from its parent. Is there a best practice for this?
Upvotes: 1
Views: 450
Reputation: 14958
I would move all common methods in A1
to another level of abstraction (let's call it ABase
), and declare in A1
and A2
their special behaviors (if any).
This way if more classes of the same type as C3
are added they don't need to redefine again methodA
.
public interface I1 {
public void methodA();
}
public abstract class ABase implements I1 {
//other methods
}
public abstract class A1 extends ABase {
public void methodA(){
//default behaviour
}
}
public abstract class A2 extends ABase {
public void methodA(){
//default behaviour
}
}
public class C1 extends A1 {
//do nothing regarding methodA, because the default behaviour in A1 is desired
//other methods
}
public class C2 extends A1 {
//do nothing regarding methodA, because the default behaviour in A1 is desired
//other methods
}
public class C3 extends A2 {
//do nothing regarding methodA, because the default behaviour in A2 is desired
//other methods
}
Upvotes: 4