The base class defines many protected methods: is it a good OOP design?

I wrote a base class that defined many protected methods . These methods are called in their subclasses. Methods define the basic operations for its subclasses. 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'm just wondering, is there a good OOP design? Read the source, we know that Sub1does not need at all Base.bar(), Sub2does not need at all Base.foo(). I think it's kind of redundant. But I do not know a better solution, can anyone give some advice? Thank!

+3
source share
4 answers

, . foo() bar() , :

class Base{

}

class Helper1  {
   public void foo(){}
}

class Helper2  {
   public void bar(){}
}

class Sub1 extends Base{
   private Helper1 a = new Helper1();
   private Helper2 b = new Helper2();

   public void po(){
     ...
     a.foo();
     ...
     b.bar();
   }
}

class Sub2 extends Base{
   private Helper2 b = new Helper2();

   public void ko(){
     ...
     b.bar();
     ...
   }
}

foo bar . . .

+3

, . : " sub2 , "

" sub2 ", , ? , , .

sub2 , , - , , - .

+2

1- , Dependecy, , Helper1, Helper2 .

2- , Create Helper1 Helper 2 , helper1 helper 2 , , Virtual, , .

3- , , , .

4 : , , , , , , , .

oop progrmming , , ABSTRACTION, .

: , , .

+1

, SOLID.

if your subclasses do not need the entire function of the base class, you can break the base class into more specific base classes or interfaces.

+1
source

Source: https://habr.com/ru/post/1760988/


All Articles