Java main() method เป็น static เสมอ เพื่อให้คอมไพเลอร์สามารถเรียกได้ โดยไม่ต้องสร้าง object หรือ ก่อนการสร้าง object ของคลาส
- ในโปรแกรม Java ใดๆ main() method เป็นจุดเริ่มต้นที่คอมไพเลอร์เริ่ม execute โปรแกรม ดังนั้นคอมไพเลอร์ต้องเรียก main() method
- ถ้า main() อนุญาตให้เป็น non-static แล้วขณะเรียก main() method JVM ต้อง instantiate คลาสของมัน
- ขณะ instantiate ต้องเรียก constructor ของคลาสนั้น จะมี ambiguity หาก constructor ของคลาสนั้นรับ arguments
- Static method ของคลาสสามารถเรียกได้โดยใช้แค่ class name โดยไม่ต้องสร้าง object ของคลาส
- main() method ใน Java ต้องประกาศเป็น public, static และ void หากขาดอย่างใดอย่างหนึ่ง โปรแกรม Java จะ compile ผ่านแต่จะโยน runtime error
ตัวอย่าง
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();
}
}
ผลลัพธ์
Welcome to TutorialsPoint Library