I wrote a base class which defined many protected methods. Those methods are called in its sub classes.
The methods define basic operations for its sub classes.
For instance:
class Base{
protected void foo(){}
protected void bar(){}
}
class Sub1 extends Base{//The sub class only needs Base.foo()
public void po(){
...
foo();
...
}
}
class Sub2 extends Base{//The sub class only needs Base.bar()
public void ko(){
...
bar();
...
}
}
class Sub3 extends Base{//The sub class needs both Base.bar() and Base.foo()
public void lo(){
...
bar();
...
foo();
}
}
I am just wondering if it is a good OOP design? Read the source, we know Sub1 doesn’t need Base.bar() at all, Sub2 doesn’t need Base.foo() at all. It’s sort of redundant I think. But I don’t know better solution, anyone could give some advice? Thanks!
Generally you should avoid these kind of object dependencies in your design. If the functionality of foo() and bar() doesn’t change in derived classes, you might want to put it in an outer class and use that one instead:
This foo & bar example does not look well. Your problem might be a bad assignment of responsibility to the objects or misuse of inheritance. Posting the real code would help to write better answers.