user5474425
user5474425

Reputation: 125

Can we create an object of the class in which main function is defined in Java?

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?

Upvotes: 3

Views: 8595

Answers (3)

Reilas
Reilas

Reputation: 6246

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();
    }
}

Upvotes: 0

Propagandian
Propagandian

Reputation: 452

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");
    }
}

Upvotes: 5

Bhanu Boppana
Bhanu Boppana

Reputation: 134

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.

Upvotes: 1

Related Questions