简体   繁体   中英

How to avoid code duplication between two similar classes that extend different ones

I'm working on a Java project where I have to implement textfields with placeholders for the login window. To do this, I got a class from this blog for my JTextField and created a second class that's basically the same, it just extends JPasswordField instead of JTextField .

As said, those classes are of course almost exactly the same, it's just that one extends JTextField , while the other one extends JPasswordField . I've been looking for a way to fix this code duplication, but can't seem to find something that works, yet I'm pretty sure it is possible.

I've thought of an abstract class, but you can't extend two classes, so that doesn't seem possible...

Any ideas?

In this case, you can reduce code duplication by using the Delegate Pattern . Put in an external class the common logic, and include an instance of it in your custom JPasswordField/JTextField.

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