What does the 'static' keyword do in a class?
In a class, the static
keyword is used to declare a static member, which belongs to the class itself rather than an instance of the class. This means that you can access a static member without creating an instance of the class.
Static members are often used to hold data or methods that are shared across all instances of a class. For example, you might use a static field to store a value that needs to be shared by all instances of a class, or you might use a static method to perform an operation that is common to all instances of the class.
Here is an example of how to declare and use a static field in a class:
class Counter {
static int count = 0;
int id;
Counter() {
count++;
id = count;
}
static int getCount() {
return count;
}
}
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
System.out.println(Counter.count); // Outputs 3
System.out.println(c1.getCount()); // Outputs 3
System.out.println(c2.getCount()); // Outputs 3
System.out.println(c3.getCount()); // Outputs 3
In this example, the count
field is a static field that is shared by all instances of the Counter
class. The getCount()
method is also a static method that can be used to access the count
field.