Reputation: 235
I have three similar classes in java. They hold the data for three different forms.
The forms themselves are inner classes of these three classes extending the JPanel
class. They have labels, text fields and buttons. To add these components to the JPanel
, I use an
addComponent()
method that sets up the GridBagConstraints
for the GridBagLayout
.
This method is the same for all three classes. I would like to have this method written only in one place but I can't think of an elegant way to do it.
One way I thought about was to make a formData superclass for the original classes to hold this method. If anyone has a better idea, I would appreciate it. I'm a beginner in java and I'm desperately trying to simplify my code.
Upvotes: 3
Views: 5545
Reputation: 19189
I can think of two ways to accomplish this:
A utility class containing frequently used, well defined, methods.
A (possibly abstract) superclass that you inherit from.
If you do non-class-specific stuff like e.g. formatting a string, an utility class might be more preferable.
If you do stuff like class-specific instantiation/computing then you probably want a superclass. If you can think of a logical name for a superclass, like FormData
in your case, then it's a good bet that a superclass is what you want.
You are right to avoid code duplication. It is almost never necessary to duplicate code, and when it becomes necessary it's probably time to look over your overall design.
Upvotes: 5
Reputation: 2476
Any time you find yourself repeating the same code in several different classes, your first thought should be to look for a way to create a superclass. You could try something like this:
public abstract class FormData {
public void addComponent(Component c) {
// do stuff
}
}
Then your inner class would simply extend FormData
, and it would get the definition of addComponent
for free!
Upvotes: 0