Java – common code when rewriting abstract methods – Design Problems
•
Java
I have an abstract class like this
public abstract Stuff { public abstract void doStuff(); }
Several classes are extending stuff, overriding dostuff() Dostuff () usually performs completely different tasks for each implementation, but shares a common part
What is the best way to achieve this?
I don't want to write something like:
public void doStuff() { doTheCommonPart(); ... }
In each extension class
Solution
Or:
> put the public code in the protected method of the Stuff class and call it from every implementation of doStuff; Either > add the public code to the abstract stuff class and call another abstract method
For example (1)
public abstract Stuff { public abstract void doStuff(); protected void commonCode() { //... } }
Or (2)
public abstract Stuff { public void doStuff() { // Do the common stuff initially... // ... // Then call the subclass implementation doRealStuff(); } public abstract void doRealStuff(); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码