Android-FAQ icon indicating copy to clipboard operation
Android-FAQ copied to clipboard

‫چرا متد main در جاوا static است ؟

Open FatemehKavoosi opened this issue 5 years ago • 2 comments

FatemehKavoosi avatar Jul 08 '20 19:07 FatemehKavoosi

ما میتوانیم کلمه کلیدی Static را قبل از متغیرها، متدها و کلاسهای تو در تو قرار دهیم. نکته اساسی که در این کلمه کلیدی وجود دارد این است که static وابسته به کلاس است و نه شی در کنار کاربرد های خاص خود، دو محدودیت نیز دارد. محدودیت اول این است که این نوع متدها نمیتوانند به طور مستقیم متغیرها یا متدهایی که static نیستند را استفاده کنند.محدودیت دوم هم بدین صورت است که متد static در جاوا نمیتواند در خود از کلمه کلیدی this و super استفاده کند. این تابع main مستقیما توسط JVM فراخوانی میشه و باید static باشه چون نیازی نیست که static نباشه.

و نباید از آن شی ساخته بشه

MohsenNooriArdestani avatar May 15 '22 04:05 MohsenNooriArdestani

Java main() method is always static, so that compiler can call it without the creation of an object or before the creation of an object of the class.

  • In any Java program, the main() method is the starting point from where compiler starts program execution. So, the compiler needs to call the main() method.
  • If the main() is allowed to be non-static, then while calling the main() method JVM has to instantiate its class.
  • While instantiating it has to call the constructor of that class, There will be ambiguity if the constructor of that class takes an argument.
  • Static method of a class can be called by using the class name only without creating an object of a class.
  • The main() method in Java must be declared public, static and void. If any of these are missing, the Java program will compile but a runtime error will be thrown.

refrence: https://www.tutorialspoint.com/why-the-main-method-in-java-is-always-static#:~:text=Java%20main()%20method%20is,where%20compiler%20starts%20program%20execution.

MohsenNooriArdestani avatar May 15 '22 13:05 MohsenNooriArdestani