Is it possible to instantiate a class object containing the main function in Java?

In a class, the main method is a part of it and can be called using the object of that class. The compiler will consider the main method as a static method. Can a class object be created where the main method exists?


Question:

I’ve been searching for an answer on whether it’s feasible to
create object
a class where
main method
is present. However, I’ve been informed that it’s compiler-dependent, meaning some compilers may permit it while others may not. Can you confirm if this is accurate?


Solution 1:


The main method serves as an entry point to the class which is similar to any other class, but with an extra method named

public static

. Although the main method is static and not included in the object instance, it should only be utilized for program initiation purposes rather than other actions.

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


Solution 2:


It is possible to instantiate an object for a class that contains a main method. The process of creating objects and utilizing them in such classes is identical to that of classes without a main method.

Frequently Asked Questions