When you make a new class with the main method in it, does it automatically create an instance of that class?
example
class TennisShoe
main
do stuff
//since it is doing stuff, is there an object that is created to start the main for doing stuff?
Printable View
When you make a new class with the main method in it, does it automatically create an instance of that class?
example
class TennisShoe
main
do stuff
//since it is doing stuff, is there an object that is created to start the main for doing stuff?
Im not sure what you mean.... i THINK you mean..does the main thread automaticly run? if thats your questiion...then yea it does.
Also if you want to run a 'main' method on a different class when u make a object you use a 'constructor'... So...
i hope this answers ur question and i hope wat i said is right... im quite new to java as well as u - WEll Goodluk with it :SCode:public class myClass{
public static void main(String[] args){
secondClass scObject = new secondClass();
//This is run When program starts
}
}
public class secondClass{
public secondClass{ // Constructor
System.out.println("test");
//THis will also run
}
}
The answer is yes. when you execute the "main" method it creates an instance of the class that that is runs in..
example..
Code:public class Main {
int index;
public Main() {
index=1;
}
public static void main(String[] args) {
for (int i=0; i < 10; i++) {
index++;
System.out.Println(index);
}
}
}
}
Quote:
//since it is doing stuff, is there an object that is created to start the main for doing stuff?
No. main() is a static method so there is no instance of the class associated with it. No instance of the class is created or needed: the behaviour of main() is behaviour of the class as a whole.
If you want an instance of the class you have to create one with new. If you don't create such an instance the main() method will not be able to access fields etc. The code in #4 doesn't compile. To be able to increment the index variable you would have to write:
Code:public class Main {
int index;
public Main() {
index = 1;
}
public static void main(String[] args) {
Main test = new Main();
for(int i = 0; i < 10; i++) {
test.index++;
System.out.println(test.index);
}
}
}