In this post under Java Language, I will show with example how to access member variables and methods when using instance main method.
But before showing the new approach lets recap the old approach. This will help in comparing old and new approach.
Below is the example showing the old approach
Old Approach
package core.language;public class InstanceMainMethodExample3 { int x = 10; int y = 20; public static void main(String[] args) { InstanceMainMethodExample3 example = new InstanceMainMethodExample3(); System.out.println(example.x); example.display(); } void display() { System.out.println(y); }}
As you can see in the main method, first I will create an instance of “InstanceMainMethodExample3” named “example” and then access the member variables “x” and methods “display” using the dot operator. Refer line 9 and 10
Now lets see the new approach
New Approach
package core.language;public class InstanceMainMethodExample3 { int x = 10; int y = 20; void main() { System.out.println(x); display(); } void display() { System.out.println(y); }}
As you can see in the new main method, I don’t create an instance of “InstanceMainMethodExample3” as it is created by JVM itself. Inside the main method, I access the member variables “x” and methods “display” directly without using the dot operator. Refer line 8 and 9
In this way we can access the member variables and methods using new main method.