TurkuBasicOOPinJava / Week 6: Methods of OO Programming /03A. Class variables = STATIC VARIABLES
KaiquanMah's picture
public static dtype STATICVARIABLEINCAPS = <value>;
f6f3443 verified
It is also possible to define 'static variables'.
These are also called 'class variables'.
Hence, they are used by using the class name, not an object reference.
Class variables are OFTEN 'public'.
The name is typically written in ALL CAPS.
class FootballMatch {
// Class variables are defined before attributes
public static int TIME_IN_MINUTES = 90;
private String team1;
private String team2;
public FootballMatch(String team1, String team2) {
this.team1 = team1;
this.team2 = team2;
}
// etc.
}
Example of using the variable:
public class Test {
public static void main(String[] args) {
// Variable can be references withou creating an object
int duration = FootballMatch.TIME_IN_MINUTES;
System.out.println("Football match takes " + duration + " minutes.");
}
}
Program outputs:
Football match takes 90 minutes.
Earlier in Java, it was typical to use class variables to define different kinds of class constants - for example the suits of the cards.
Later, 'enum classes' were introduced for this (these are discussed next week).
Let's see another example of class variables.
Now, the value of the class variable is changed each time an object is created.
Note that since it is a class variable, there is only 1 SHARED VALUE for ALL OBJECTS CREATED from the class.
..BUT U CAN CHANGE FROM THE 'DEFAULT SHARED VALUE' TO AN OBJECT-SPECIFC VALUE/SMTH ELSE!!!!!!!!!!!
class Bubble {
public static int BUBBLES_NOW = 0;
private int diameter;
public Bubble(int diameter) {
this.diameter = diameter;
Bubble.BUBBLES_NOW++;
}
}
Example about using the variable:
public class TestClass {
public static void main(String[] args) {
Bubble bubble1 = new Bubble(5);
System.out.println(Bubble.BUBBLES_NOW);
Bubble bubble2 = new Bubble(21);
System.out.println(Bubble.BUBBLES_NOW);
Bubble bubble3 = new Bubble(15);
System.out.println(Bubble.BUBBLES_NOW);
Bubble bubble4 = new Bubble(7);
System.out.println(Bubble.BUBBLES_NOW);
}
}
Program outputs:
1
2
3
4