This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Static variables for instance are also called 'class variables'. They only exist once per class, not per instance.
That makes static members instance independent, they share the same value among all instances of your class.
A good example for static methods are utility methods such as those in the Arrays or Collections class.
To perform Collections.emptyList() you do not need an instance because this method does not require any state. Hence it is a good decision to mark it static.
JDBCSupport - An easy to use, light-weight JDBC framework -
Agree with Sebastian Janisch. About methods: if a method takes no information from the state of an object (it uses no instance fields) and it imparts no information to the state of an object (it alters or manipulates no instance fields) then you should consider making it static
Note that many books use the main method a lot, because it is quicker to put a little code example in the main method than to write proper object-oriented code. So they have examples where all their methods are marked "static" because you cannot access instance fields, instance members, the keyword "this" and the keyword "super" in a static method or block.
When you have an object that you only want 1 instance of, you use static.
A very good example of this is a database connection pool. You may want many connections but since creating connections is very expensive operation, so you want to reuse them. That is where the database pool comes in (a pool of database connections).
your database is configured for 110 connection and your database pool is configure for 100 connections. If you have 2 instances of the database pool, you can imagine the problems that can occur when one of those pools ask the database for its 111th connection
There is a very popular design pattern based on the static keyword it is called a singleton. Here is one article.
rakesh lawr wrote:I want to know about the usage of STATIC keyword in a class/method/variable...
Campbell and Sebastian has already defined why the method should be static. I would only suggest to
remember when you make method static is that you must make sure there
is no chance you’ll want it to behave polymorphically.