Java main() method luôn là static, để compiler có thể gọi nó mà không cần tạo object hoặc trước khi tạo object của class.
- Trong bất kỳ Java program nào, main() method là điểm bắt đầu từ nơi compiler bắt đầu thực thi chương trình. Vì vậy, compiler cần gọi main() method.
- Nếu main() được phép non-static, thì khi gọi main() method, JVM phải instantiate class của nó.
- Khi instantiate, nó phải gọi constructor của class đó, sẽ có ambiguity nếu constructor của class đó nhận argument.
- Static method của một class có thể được gọi bằng tên class mà không cần tạo object của class.
- main() method trong Java phải khai báo public, static và void. Nếu thiếu bất kỳ cái nào, Java program sẽ compile nhưng sẽ ném runtime error.
Ví dụ
class Book {
public static void getBookInfo() { //static method
System.out.println("Welcome to TutorialsPoint Library");
}
}
public class Test {
public static void main(String[] args) {
//Call static method of Book class using class name only
Book.getBookInfo();
}
}Kết quả
Welcome to TutorialsPoint Library