CoolFace
Apppublic

KaiquanMah/TurkuBasicOOPinJava

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
03A. Class variables = STATIC VARIABLES93 linesDownload Raw Back to Week 6: Methods of OO Programming
1It is also possible to define 'static variables'. 2These are also called 'class variables'. 3Hence, they are used by using the class name, not an object reference.4 5Class variables are OFTEN 'public'. 6The name is typically written in ALL CAPS.7 8class FootballMatch {9    // Class variables are defined before attributes10    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 25Example of using the variable:26public class Test {27    public static void main(String[] args) {28        // Variable can be references withou creating an object29        int duration = FootballMatch.TIME_IN_MINUTES;30        System.out.println("Football match takes " + duration + " minutes.");31    }32}33Program outputs:34Football match takes 90 minutes.35 36 37 38 39 40 41 42 43 44 45Earlier in Java, it was typical to use class variables to define different kinds of class constants - for example the suits of the cards. 46Later, 'enum classes' were introduced for this (these are discussed next week).47 48Let's see another example of class variables. 49Now, the value of the class variable is changed each time an object is created.50 51Note 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 56class 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 68Example about using the variable:69public 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 85Program outputs:86187288389490 91 92 93