What is difference between static method and static
variable?
Answer Posted / joh-b tanzania
The static keyword denotes that a member variable, or method, can be accessed without requiring an instantiation of the class to which it belongs.
In simple terms, it means that you can call a method, even if you've never created the object to which it belongs! Every time you run a stand-alone application (which requires a static main method), the virtual machine can call the main method without creating a new application object. Of course, unless the application's methods are all static, you will need to create an instance of it at some point.
With regard to member variables, it means that they can be read from, and written to, without creating an object. You may have noticed that many classes create constants that can be read, without creating an object.
static final int VERSION = 2;
Static member variables are shared by all instances of the class to which they belong. When writing classes, this can be a handy feature. Consider the following example, where a counter is used to track how many myObject instantiations have taken place.
public class myObject
{
static int objectCount = 0;
public myObject()
{
objectCount++;
}
public String toString()
{
return new String ("There are " + objectCount + " objects");
}
}
| Is This Answer Correct ? | 3 Yes | 1 No |
Post New Answer View All Answers
Can we extend a class with private constructor?
How do I get 64 bit java?
When a lot of changes are required in data, which one should be a preference to be used? String or stringbuffer?
Is char a data type in java?
How to call one constructor from the other constructor ?
What is object class in java?
Can this keyword be used to refer static members?
Explain when noclassdeffounderror will be raised ?
How can we make string upper case or lower case?
What is java command?
Can we call the constructor of a class more than once for an object?
What is meant by data hiding/encapsulation?
What is user defined exception in Java?
Explain the use of shift operator in java. Can you give some examples?
What is an accessor?