
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Declare Main Method as Private, Protected or Without Access Modifier in Java
Java provides various access specifiers namely private, public and protected etc...
The Private modifier restricts the access of members from outside the class. A class and interface cannot be public.
The Public access modifier can be associated with class, method, constructor, interface, etc. public can be accessed from any other class.
The protected access modifier can be associated with variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.
The default access modifier does not have keyword a variable or method declared without any access control modifier is available to any other class in the same package.
Therefore, if you declare a method public it can be accessed from anywhere outside the class. As we know that JVM accesses/invokes the main method directly if the main method is public JVM can invoke it from anywhere.
Declaring the main method private or, protected
You can define the main method in your program without private, protected or, default (none) modifier, the program gets compiled without compilation errors.
But, at the time of execution JVM does not consider this as the entry point of the program. It searches for the main method which is public, static, with return type void, and a String array as an argument.
public static int main(String[] args){ }
If such a method is not found, a run time error is generated.
Example
In the following Java program, the class Sample contains the main method which is public.
public class Sample{ private static void main(String[] args){ System.out.println("This is a sample program"); } }
Output
On executing, this program generates the following error.
Error: Main method not found in class Sample, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application