简体   繁体   中英

shared methods between classes in java

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.

I can think of two ways to accomplish this:

  1. A utility class containing frequently used, well defined, methods.

  2. A (possibly abstract) superclass that you inherit from.

If you do non-class-specific stuff like eg 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.

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!

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