Is it possible to create object of class in which main method resides.I have been searching for this answer but I have been told that it depends on compiler some compiler will allow while others will not.Is that true?
Asked
Active
Viewed 5,777 times
3
-
1Nope, just call `new MainClass()` or whatever the main class name is. Some example code will help. – markspace Aug 05 '19 at 05:30
-
1No, it's not true that it depends on compiler. Did you try creating an object of that class? What happened when you did? – Dawood ibn Kareem Aug 05 '19 at 05:30
-
Possible duplicate https://stackoverflow.com/questions/2550310/can-a-main-method-of-class-be-invoked-from-another-class-in-java – abj1305 Aug 05 '19 at 05:52
3 Answers
5
Yes, you can. The main method is just an entry point. The class is like any other, except it has an additional public static
method. The main method is static and therefore not part of the instance of the object, but you shouldn't be using the main method anyway except for starting the program.
public class Scratchpad {
public static void main(String[] args) {
Scratchpad scratchpad = new Scratchpad();
scratchpad.someMethod();
}
public Scratchpad() {
}
private void someMethod() {
System.out.println("Non-static method prints");
}
}

Community
- 1
- 1

Propagandian
- 444
- 3
- 10
1
Yes, you can create object for the class which has main method. There is no difference in this class and a class which don't have main method with respect to creating objects and using.

Bhanu Boppana
- 134
- 1
- 2
- 10
0
The main
method is not limited to one class, you can place it within any class.
As for different JVM implementations having different standards, that I am unsure of.
It doesn't sound correct, being unable to instantiate the class within itself would create constraints.
class Example {
public static void main(String[] args) {
Example example = new Example();
}
}

Reilas
- 3,297
- 2
- 4
- 17