Search code examples
javalanguage-concepts

Java, Class objects that have different methods to each other?


This may seem like an odd question, but I'm trying to practice writing reusable code, or least trying to practice thinking about it in the right way, if you know what I mean? I have an assignment that involves writing a text interface with a couple of different menus. So there are two approaches to this: (1) a class for each menu (sloppy) or (2) a class which contains the information for all the menus (not as sloppy).

Now that I am writing this, it feels like it might be bad practice, BUT is it possible to have one class which contains the basic components of a menu (a title, a list of MenuOptions etc), but the methods can be added at another time?

Alternatively, if this is not possible/advisable, which would be the generally preferred way of doing something like this, (a) separate classes for separate menus, or (b) one big class which contains all the code for the different menus?


Solution

  • I think I understand what you mean, but I also think that when you say but the methods can be added at another time? you mean that what the methods do is added at another time.

    Menus, in your case, usually need to take care of some basic things, such as

    • Showing the actual menu text (let's call it title);
    • Showing a tool tip;
    • Doing something when clicked.
    • Child sub menu items.

    To achieve this, you could use either or a mix of two things:

    1. The strategy design pattern.
    2. Abstract classes.

    The strategy design pattern allow you to specify a behaviour, and then pass it along to some class which knows what to do with that behaviour. In short, your behaviour could be what happens when the menu item is clicked. So basically, your menu class will not know what to do when it is clicked, but it will know to whom the call will be delegated. This approach would allow you to have one Menu class and several behaviours it can access.

    Using abstract classes is similar to using the design pattern, however, you would end up creating a new concrete class for each different menu you want to have.

    Thus, I think that the best result would be somewhere in between.

    For instance you could create your Menu parent class as abstract, with properties such as Title, Tooltip, etc. You could then add a method called onActionPerformed which takes in some object which handles what happens when the menu item has been clicked. Lastly, you could create abstract methods such as onBeforeActionPerformed and onAfterActionPerformed, this would essentially be interceptors which would allow you to do logic just before and after the event handling.

    You could then extend the Menu class with things such as NonInterceptibleMenu and the likes to handle the different scenarios.