java - Best practise regarding static context -
when writing standalone java application, see lot of beginners code in static context. used around problem creating instance of class in main, , working constructor.
i've added few examples of simple standalone program, , know if there best practises "leaving" static context.
i know if there things standalone java program should doing in static context or in main method, it's function besides being entry point of every standalone java program.
any reading material welcome!
import javax.swing.jframe; import javax.swing.jlabel; public class examplestatic { jlabel label; public static void main(string[] args) { //option 1 - work static context: jframe frame = new jframe(); frame.setbounds(10,10,100,100); frame.setdefaultcloseoperation(jframe.exit_on_close); jlabel staticlabel = new jlabel("static"); frame.add(staticlabel); frame.setvisible(true); //option 2 - create instance, call initialisation function examplestatic e = new examplestatic(); e.initialise(); //option 3 - create instance, handle initialisation in constructor new examplestatic(true); } public examplestatic(){} public examplestatic(boolean init) { jframe frame = new jframe(); frame.setbounds(10,10,100,100); frame.setdefaultcloseoperation(jframe.exit_on_close); label = new jlabel("constructor"); frame.add(label); frame.setvisible(true); } public void initialise() { jframe frame = new jframe(); frame.setbounds(10,10,100,100); frame.setdefaultcloseoperation(jframe.exit_on_close); label = new jlabel("init function"); frame.add(label); frame.setvisible(true); } }
option 2 , option 3 both fine, both provide loose coupling if want use instance somewhere else in other classes can use easily. if write in main method going loose scope , reusability.
Comments
Post a Comment