简体   繁体   中英

Is there a solution to empty methods in subclass?

I have a super class, with 2 subclasses. If condition foo is true I want one of the subclass to take some action while other subclass should do nothing:

public void doFoo() {
   // some 10 lines common to both subclasses.
   boolean foo = checkFoo();

   /**
    *  if foo is true, subclass1 should do something. subcass2 does nothing.
    */ 

   // some 10 lines common to both subclasses.
}

The solution I came up with:

public void doFoo() {
   // some 10 lines common to both subclasses.
   boolean foo = checkFoo();

   if (foo) {
      doSomething();
   } 

   // some 10 lines common to both subclasses.
}

class subclass1 extends superclass {
   public void doSomething()  {
     // some lines of code.
   }

}

class subclass2 extends superclass {
   public void doSomething()  {
     // do nothing
   }
}

Any cleaner, better, more standard solution to this common problem?

What you are describing has a name: it is the Template Method pattern . Design patterns aren't so hyped these days as once they were, but the Template Method pattern is still a tried and true approach to the general sort of problem you describe.

If you want to avoid writing empty doSomething() methods in subclasses, then one way to go about it would be to put an empty doSomething() method on the superclass instead. That can serve multiple subclasses (supposing that you have more than two overall to worry about), but personally, I'm inclined to frown on that a bit. Overriding non-abstract methods ought to be the rare (at best) exception, not a common practice.

That is the "correct" approach. But some notes:

  • doSomething() could be abstract (if you want to enforce that each subclass has to provide a specific implementation)
  • doFoo() on the other hand should be final in order to prevent subclasses from changing that behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM