KaiquanMah commited on
Commit
f6f3443
·
verified ·
1 Parent(s): e8ecd2c

public static dtype STATICVARIABLEINCAPS = <value>;

Browse files
Week 6: Methods of OO Programming/03A. Class variables = STATIC VARIABLES ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ It is also possible to define 'static variables'.
2
+ These are also called 'class variables'.
3
+ Hence, they are used by using the class name, not an object reference.
4
+
5
+ Class variables are OFTEN 'public'.
6
+ The name is typically written in ALL CAPS.
7
+
8
+ class FootballMatch {
9
+ // Class variables are defined before attributes
10
+ public static int TIME_IN_MINUTES = 90;
11
+
12
+ private String team1;
13
+ private String team2;
14
+
15
+ public FootballMatch(String team1, String team2) {
16
+ this.team1 = team1;
17
+ this.team2 = team2;
18
+ }
19
+
20
+ // etc.
21
+ }
22
+
23
+
24
+
25
+ Example of using the variable:
26
+ public class Test {
27
+ public static void main(String[] args) {
28
+ // Variable can be references withou creating an object
29
+ int duration = FootballMatch.TIME_IN_MINUTES;
30
+ System.out.println("Football match takes " + duration + " minutes.");
31
+ }
32
+ }
33
+ Program outputs:
34
+ Football match takes 90 minutes.
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+ Earlier in Java, it was typical to use class variables to define different kinds of class constants - for example the suits of the cards.
46
+ Later, 'enum classes' were introduced for this (these are discussed next week).
47
+
48
+ Let's see another example of class variables.
49
+ Now, the value of the class variable is changed each time an object is created.
50
+
51
+ Note that since it is a class variable, there is only 1 SHARED VALUE for ALL OBJECTS CREATED from the class.
52
+ ..BUT U CAN CHANGE FROM THE 'DEFAULT SHARED VALUE' TO AN OBJECT-SPECIFC VALUE/SMTH ELSE!!!!!!!!!!!
53
+
54
+
55
+
56
+ class Bubble {
57
+ public static int BUBBLES_NOW = 0;
58
+
59
+ private int diameter;
60
+
61
+ public Bubble(int diameter) {
62
+ this.diameter = diameter;
63
+ Bubble.BUBBLES_NOW++;
64
+ }
65
+ }
66
+
67
+
68
+ Example about using the variable:
69
+ public class TestClass {
70
+ public static void main(String[] args) {
71
+ Bubble bubble1 = new Bubble(5);
72
+ System.out.println(Bubble.BUBBLES_NOW);
73
+
74
+ Bubble bubble2 = new Bubble(21);
75
+ System.out.println(Bubble.BUBBLES_NOW);
76
+
77
+ Bubble bubble3 = new Bubble(15);
78
+ System.out.println(Bubble.BUBBLES_NOW);
79
+
80
+ Bubble bubble4 = new Bubble(7);
81
+ System.out.println(Bubble.BUBBLES_NOW);
82
+ }
83
+ }
84
+
85
+ Program outputs:
86
+ 1
87
+ 2
88
+ 3
89
+ 4
90
+
91
+
92
+