Okay, I’m NOT a Java noob, it just so happens that I’ve forgotten a tad bit about core Java while I was learning more fun stuff like MySQL, Servlets, Java EE, JDBC etc etc; so don’t frame your answers as if I were a beginner. Now the question…..
I’m writing a class (lets say ThisIsAJFrameExtendingClass) which extends JFrame, and to minimize confusion with my overall project, I also want to park some other utility methods in ThisIsAJFrameExtendingClass. I intend this class (ThisIsAJFrameExtendingClass) to seek certain inputs from the user following which; commit suicide (ie dispose()). So, my question is, how can I independently use the utility methods inside the class without any JFrame popping up on the user screen.
I’ld like a solution with the help of multiple constructors inside the ThisIsAJFrameExtendingClass class, where, invoking the argument-less constructor return JFrame and the second constructor with a boolean argument gives access to the utility methods.
[UPDATE]
Ohh…. I just had a thought, the utility method has a return type of ArrayList so, assuming the utility method is called utilMethod() then:
ArrayList<String> pring = new ThisIsAJFrameExtendingClass().utilMethod();
will the above code output any JFrame?
You could make the utility methods
static, in which case they can be invoked usingThisIsAJFrameExtendingClass.<method name>without creating an instance.The stuff about constructors doesn’t really make sense to me. A class’s constructor always returns an instance of that class. It can’t return “something else” because of a parameter you pass in.
[Edited to respond to the question’s Update]:
new ThisIsAJFrameExtendingClass()will create an instance of your class, running its constructor (and the default constructor of all superclasses). This may allocate other resources (such as other Swing components or whatever) that each constructor in the inheritance tree requires. So aJFrameis created, but if you only callutilMethod()and never hang on to the reference to the frame, it will be garbage collected and its resources freed at some point in the future.Creating a JFrame instance to call a single utility method on it isn’t a particularly efficient way to go about things, but it won’t cause any problems. (As Chad says, by default a
JFrameisn’t visible, so users won’t see anything if you’re using it in “util” mode).As to returning an
ArrayList, as a general rule when using collections, you should return the highest level interface that makes sense rather than a concrete class. So in this case, consider returningList<String>or evenCollection<String>.