1. Using Instance Initializer block
Instance
Initializer block is used to initialize the instance data
member. It runs each time when object of
the class is created.
public class
MainMethodTest {
/** Instance block called while creating the Object. */
{
System.out.println("Inside Instance Initializer block!!");
}
public static void
main(String[] args) {
System.out.println("Main method executed!!");
}
}
Output:
Main method executed!!
In above program, there is main() method along
with Instance Initializer block. The Instance Initializer
block is not called while executing the main method which proves that the class is not initialised while executing the main method.
2. By using abstract keyword
We cannot create the instance of an abstract
class. Because
it's abstract and an object is concrete. An abstract class is sort of like a
template, or an empty/partially empty structure, you have to extend it and
build on it before you can use it.
public abstract class
MainMethodTest {
public static void main(String[]
args) {
System.out.println("Main method executed!!");
}
}
Output:
Main method executed!!
However we are able to execute the main method inside the abstract
class which proves that there is no need to create the object while executing
the main method.
3. Using Constructor
A default (no-argument) constructor is called while
creating the object of any class.
public abstract class
MainMethodTest {
public
MainMethodTest() {
System.out.println("Constructor MainMethodTest!!");
}
public static void
main(String[] args) {
System.out.println("Main method executed!!");
}
}
Output: Main method executed!!
The constructor is not called while executing main
method. Hence the instance of class is not created while execution of main
method.
No comments:
Post a Comment