This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
class A{ public static void main(String args[]){ int i = 10; A a1 = new A(); A a2 = new A(); } A(){ System.out.println("Hello");;; } } This program instanciates the main class. What's the point of instanciating the main class? Does this mean the programm which is defined in main will run two times?
This program instanciates the main class. What's the point of instanciating the main class?
Well.... kinda... actually the program instantiates two objects of class A... I think that one point of confusion is that the class of the type of objects you are creating contains a main() method which creates objects of that class. According to OO terminology, a class is basically a blueprint that objects of that type are created from. Another point of confusion involves the main() method... When you run a java program, what goes on "behind the scenes" is this... the JVM starts, loads the class you specified (and any others that it needs), and then calls the main() method of the specified class. The main() method is specifically used in java as a point that the JVM can start at.
Does this mean the programm which is defined in main will run two times?
No... the code defined in the main() method will only run once... when the JVM calls it... however, the code in the constructor A() will run twice.
HTH, -Nate
-Nate
Write once, run anywhere, because there's nowhere to hide! - /. A.C.
Cindy Glass
"The Hood"
Sheriff
Joined: Sep 29, 2000
Posts: 8521
posted
0
Just a point. Executing a class that has a main does not cause an instance of that class to be created. Only the new operator does that. Lot's of people prefer to have a separate driver class that does NOTHING except have a main. Less confusion that way. Since only the main method of the class that was called from the prompt gets executed, this allows the opportunity to put a main method in other classes that are NOT the driver class. Those mains can be used during construction (if you are very clever) to "self-test" the class, and can be left in the class because they don't hurt anything and don't get used by the application in it's normal running mode.
"JavaRanch, where the deer and the Certified play" - David O'Meara