سلام
توضیحی بسیار خوبی بود.
خیلی از دوستان در مورد متغیر static، دو اشتباه معمول میکنن، یکی اینکه فکر میکنن متغیر های static همان حالت Constant است و مقدار آن همیشه ثابت است، و دوم اینکه برای دسترسی به این متغیر، سعی بر ایجاد یک شی از کلاس را دارند! که این کار به هیچ عنوان امکان پذیر نیست! برای دسترسی به متغیر های static فقط میتوان به طریقی که دوستمون در پست قبلی گفتند، عمل کد.
اما این را باید در نظر داشت، برای اینکه قصد دسترسی به متغیری از خارج از کلاس مربوطه را داشته باشیم، این راه خوبی نیست که متغیری را static تعریف کنیم، به دلایل مختلف. اما اگر متغیری و یا حتی تابعی، در اکثر نقاط برنامه مشترک بوده و به کررات از آن استفاده میشود، به طور حتم بهتر است که متغیر به صورت static تعریف شود.
البته، این یکی از دلایل استفاده از متغیر های static است. این متغیر ها و توابع کاربردهای فراوانی دارند که در صورت استفاده صحیح از آن بسیار مفید خواهند بود و عکس این قضیه صادق است، یعنی اگر استفاده نادرست از این نوع شود؛ مشکلات خواص خود را خواهد داشت.
توضیح گوگل در مورد متغیر های static:
Avoid Internal Getters/Setters
In native languages like C++ it's common practice to use getters (i = getCount()) instead of accessing the field directly (i = mCount). This is an excellent habit for C++ and is often practiced in other object oriented languages like C# and Java, because the compiler can usually inline the access, and if you need to restrict or debug field access you can add the code at any time.
However, this is a bad idea on Android. Virtual method calls are expensive, much more so than instance field lookups. It's reasonable to follow common object-oriented programming practices and have getters and setters in the public interface, but within a class you should always access fields directly.
Without a JIT, direct field access is about 3x faster than invoking a trivial getter. With the JIT (where direct field access is as cheap as accessing a local), direct field access is about 7x faster than invoking a trivial getter.
Note that if you're using
ProGuard, you can have the best of both worlds because ProGuard can inline accessors for you.
موفق باشید.