Why is it necessary to create automatic instance of main function? Can't we make its data members, an object variable? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why is it necessary to create automatic instance of main function? Can't we make its data members, an object variable?

since static is used before main function, its members does not require an object to execute..but why we add static before main()?..Is it necessary to make its data members as instance variable?..couldn't we make it an object member..

24th May 2018, 2:45 AM
Komal Asthana
Komal Asthana - avatar
2 Answers
+ 4
Disclaimer: This is what I understand so far. "Static" marks code that is not associated with its containing object, and outer classes are automatically static because no object contains them. Following, Java does not create an instance of the top-level outer class--the one containing main()--instead, Java looks for the main() signature in all the top-level classes then calls into the class *definition* directly, just calling unattached code. The "automatic instance" term (I know what is meant) bothers me because that sounds like creating a Singleton (as with static code, there can be only one of it). But if an object were created here, I think it would be too easy to create a God Object* ... when I think of main() as more like the transition point; the single entry/exit bridge. * God Object (programming antipattern): https://en.m.wikipedia.org/wiki/God_object
24th May 2018, 5:18 AM
Kirk Schafer
Kirk Schafer - avatar
+ 2
Loosely speaking, the main method is the entry point for execution, so how can you create an object before your program begins? main() must be accessed statically to enter the program, and THEN other code/objects can interact. When practicing code, I find it useful to make another class with the code I am making and create the object from main e.g. public class MyMainClass { public static void main(String [] args) { NewClass obj = new NewClass(); obj.calculate(4,5); ... } class NewClass { public int calculate(int i, int j) { // code } } This way you can experiment with making instance members and more complex code without everything being static. In fact this is really the way Java should be done, through objects, main is just the start/execution point
24th May 2018, 7:36 AM
Dan Walker
Dan Walker - avatar