Why Static variables/methods must always be refered to through the class name?

I have been through many companies in my career as a Technical Architect and have seen many coding conventions followed. Some use the standard Sun coding conventions, some use Hungarian notation (yes it is still followed) and so on. Having a coding convention is one thing and following it is the other. In the company that I am currently working in we follow Hungarian Notation. Just because our CTO has been a C-Programmer all his life and decided for some reasons to jump into Java but old habits remain he still uses Arrays instead of ArrayList or Vectors and copies the elements one by one when he wants to dynamically increase the size of the Array. more on this later as I can write a book on the things that I like about him 😉 Lets get back to the topic of why is it emphasized that Static Variables/Methods must always be referred through class names and not by variable instances for example it is advised to write


then to code lit like




I was involved in a bug about getting deadlocks in the database when we were committing some transactions. It turned out to be a threading issue. There were many threads committing in the database at the same time on the same rows. As I went through the code the block of code that was committing the data was infact surrounded by a synchronized block. Here is the exact code-snippet:


remember we were using the Hungarian Notation and this means that the field was declared static. But that wasn’t the case it was declared as:

private Object s_logUsageSync = new Object();

causing the deadlocks in the database. If the field was accessed by class name then the compiler could have caught the issue at the compile time and stopped the programmer from introducing a bug in the code. So always remember there is a reason why people have made these coding conventions and violating these may get you into trouble some day 🙂

Why Static variables/methods must always be refered to through the class name?

One thought on “Why Static variables/methods must always be refered to through the class name?

  1. I have seen similar situations all to often. IMHO the problem with hungarian notation is that it relies on the developer providing exactly the right name; which is then relied upon by others.

    As you say, to then access the field by instance prevents the only sanity check from working.

    Most IDE’s create warnings for this sort of thing!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s