This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why instanciate the MAIN-Class?

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic