Reputation: 357
I understand the point of public static void main
in my starting class - to have code which is executed when the program is run.
Some articles I read online state that any class can have a main class. I created a second class which is called from the first class and created an instance of it, but the code in the second classes main method doesn't run. Am I misunderstanding how this method works in a class other than the primary class?
public class Main {
public static void main(String[] args) {
aClass newClass = new aClass();
}
}
public class aClass{
public static void main(String[] args) {
System.out.println("hello");
}
}
Upvotes: 3
Views: 2461
Reputation: 339432
The Java team at Oracle has been adding features as part of the paving the on-ramp initiative to make learning Java easier.
main
methodIn Java 11+, the java
tool implicitly invokes the javac
tool when asked to run a .java
source file. The compiled class is cached in memory. Then its main
method is invoked.
See: JEP 330: Launch Single-File Source-Code Programs.
In Java 22+, you can automatically compile and launch multiple class files, extending the single-file feature described above.
See: JEP 458: Launch Multi-File Source-Code Programs.
Upvotes: 0
Reputation: 545885
It’s true that “any class can have a main class”. But only one main
method is run, regardless of how many classes have one.
And which main
method is run depends on the designated entry point of your application, i.e. what you explicitly indicate as the entry point when running your code via java name.of.class
, or whatever your JAR manifest indicates as being the entry point.
Conversely, you can provide a class with a static initialisation block. This block will be run once, the first time the class is loaded:
public class Main {
public static void main(String[] args) {
new aClass();
new aClass();
}
}
public class aClass{
static {
// Run only once!
System.out.println("hello");
}
}
This code will run even when you don’t instantiate your class but, say, call a static method on it. But if nothing in your code ever refers to aClass
at all, its static initialiser will not be run.
Upvotes: 2
Reputation: 311853
The main
method is called on one class by the JVM (unless you call it explicitly, of course).
If you want the code to be called when you instantiate aClass
, you need to move the code to the constructor:
public class aClass{
public aClass() {
System.out.println("hello");
}
}
or, of course, call aClass.main
explicitly:
public class Main {
public static void main(String[] args) {
aClass.main(args);
}
}
Upvotes: 1