Skip to content

Commit d9bc11a

Browse files
authored
Merge pull request cherryWood55#8 from nirudi98/master
Description About Java Class Variables
2 parents e38ded7 + 6c8ac9e commit d9bc11a

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

ClassVariableInJava.txt

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
--class variables in Java--
2+
3+
Class Variables are an important concept in java programming. This Class variables also known as static variables are declared
4+
with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class
5+
variable per class, regardless of how many objects are created from it.
6+
7+
--Important Terminology--
8+
When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables.
9+
In the case of the 'Car' class, the instance variables are cadence, gear, and speed.
10+
Each 'car' object has its own values for these variables, stored in different memory locations.
11+
12+
variables that are common to all objects is gained by the static modifier.
13+
Fields that have the static modifier in their declaration are called static fields or class variables.
14+
15+
16+
17+
For example, suppose you want to create a number of 'Car' objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole. For this you need a class variable, numberOfBicycles, as follows:
18+
19+
20+
Example Syntax
21+
public class Car {
22+
23+
private int cadence;
24+
private int gear;
25+
private int speed;
26+
27+
// add an instance variable for the object ID
28+
private int id;
29+
30+
// add a class variable for the
31+
// number of Car objects instantiated
32+
private static int numberOfCars = 0;
33+
...
34+
}
35+
36+
37+
Class variables are referenced by the class name itself, as in
38+
39+
Car.numberOfBicycles

0 commit comments

Comments
 (0)