Is it possible to have a class with no main method in Java and still working perfectly??
Printable View
Is it possible to have a class with no main method in Java and still working perfectly??
You need a main() method if you want to start the class with the java command:
java TheClass
You don't need a main() method if another class creates an instance of that class:
TheClass aref = new TheClass();
also an applet does not use a main() method.
What does "work perfectly" mean?
Thank you Norm for your valuable reply, but if main method is required to start a program in Java then my problem is with this code:
class WithoutMain
{
static {
System.out.println("Hello Java");
System.exit(0);
}
}
It is working without any error or warning on dos. But eclipse is not able to run it. If this code is working in command prompt, why is it not so with eclipse?
Sorry, I don't know anything about the IDE.
I never use static blocks so I forgot about them. I always use a main() method in any class I want to execute with the java command.
Thank you Norm for your replies, I really appreciate it.
Blocks are two types one is static and non-static,
when u use static blocks inside the class till Jdk 1.6 version it will execute with out main(), but from jdk 1.7 version it wont execute. all execution starts from main(). but always static block will execute first.
first you check jdk version, if jdk 1.7 you are using.. It wont execute.
first , I executed this program with cmd,
This is the result
D:\>javac WithoutMain.java
D:\>java WithoutMain
Error: Main method not found in class WithoutMain, please define the main method
as:
public static void main(String[] args)
.............................................................................................................................
With eclipse:
Error: Main method not found in class WithoutMain, please define the main method as:
public static void main(String[] args)
...............................................................................................................................
if you are using jdk version below 1.7, then static block will execute with out main().
..................................................................................................................................