I have two classes: JDialog and JFrame (see below). Now I want them to get some extra functionality, but I want the two classes both to extend my code, without writing the code twice. Is there a way to do that?
java.awt.Window » java.awt.Dialog » javax.swing.JDialog
java.awt.Window » java.awt.Frame » javax.swing.JFrame
(PS: Actually, I want to “rewrite” the source code of java.awt.Window, adding extra functionality. I know that’s not possible, but that would be a “solution”, because if I do so, both JDialog and JFrame would extend my brand new methods.)
Example:
Suppose I want to add the method moveWindowToMagicPositionOnScreen(), moving the window to a user-friendly position on the screen—I know, it’s just an example. I want the method to apply to both JDialog and JFrame. Using inheritance, I must write two classes, for example MagicJDialog and MagicJFrame, each implementing the method moveWindowToMagicPositionOnScreen() in exactly the same manner. Well, that’s pretty redundant. So I don’t want to have the code written twice. In some way, I want one class to use the code of the other class.
The interface / delegate / composition ideas are probably the “cleanest”. But an acceptable and arguably simpler alternative is to make a utility class with a static method.
In practice, I’d probably put the calculation logic into another method,
computeMagicPositionOnScreen(). If it makes sense (it may not) this static utility class could actually be a “real” (non-static) class, say MagicPositionCalculator, that might have multiple instances, say one per each screen, one for really large screens, one for power-users, etc…