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


Please Help Members By Posting Answers For Below Questions

What is considered an anti pattern?

728


What is a vector in java?

800


Can two objects have same hashcode?

772


What is meant by data hiding in java?

882


What is maximum size of arraylist in java?

728


What are the legal operands of the instanceof operator?

804


What are the benefits of java?

816


Implement two stacks using a single array.

813


When should a function throw an exception?

844


What do you mean by chromounits in java8?

739


What are measurable parameters?

805


Can we compare two strings in java?

781


Explain what pure virtual function is?

810


What is public static?

770


What is the meaning of immutable regarding string?

761