[Solved] new instance of the class in java main method


In java a class has fields and methods (or functions). Keyword ‘static’ can be added to both of these entities.

Entities marked with keyword ‘static’ are class related and other entities are instance related. For accessing static fields or methods of a class we require only the class and its instance (created by using new keyword) is not required to be created.

Methods and fields which are not marked static belong to an active instance of the class.

Now suppose there is a class Test.java and we have no instance of it. We can call any of its method which is marked as static. Try thinking an answer to : “From inside an static method (without an instance of the class) how can we call a method or how can we access a field which belongs to some instance?”

For acessing non static field or method from an static method we need an instance. If the ‘calling method’ is non static then it must have been invoked on an object. If now we call another method from this non static ‘calling method’ we can eaisly do that as that method will be invoked on the same object as on which the ‘calling method’ has been invoked upon.

As mentioned by Xavi in his answer you can also refer to
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html for understanding about ‘static’.

All non static methods and fields have ‘this’ (https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html) associated with them, which refers to the current active instance of the class.

Hence ‘main’ method being static can not call any non static method without instance of the class ‘Test’

solved new instance of the class in java main method