Search code examples
javatypesstaticprimitive-typesmodifiers

Java Static Elements Getting accessed by different class


In Java Static elements are getting accessed by specifying only the Class name followed by dot operator.

Assume, I have a Class named ClassA with a static primitive type int a = 10;

What If I have other two class ClassB and ClassC access the element a at same time and make some change, will the change made by ClassB also impacts in the ClassC ?


Solution

  • What If I have other two class ClassB and ClassC access the element a at same time and make some change, will the change made by ClassB also impacts in the ClassC ?

    There's only one ClassA.a, because it's a static member. The change made by ClassB impacts ClassA.a. ClassC will see the change because it's looking at that same member.

    The scenario you describe is better expressed in code and diagrams:

    The classes:

    class ClassA {
        static int a = 10;
    }
    
    class ClassB {
        static void look() {
            System.out.println("B sees " + ClassA.a);
        }
        static void change() {
            ClassA.a = 42;
        }
    }
    
    class ClassC {
        static void look() {
            System.out.println("C sees " + ClassA.a);
        }
        static void change() {
            ClassA.a = 67;
        }
    }
    

    Using them:

    ClassB.look(); // "B sees 10"
    ClassC.look(); // "C sees 10"
    ClassB.change();
    ClassB.look(); // "B sees 42"
    ClassC.look(); // "C sees 42"
    ClassC.change();
    ClassB.look(); // "B sees 67"
    ClassC.look(); // "C sees 67"
    

    Diagrams:

                             +----------+
                             |  ClassA  |
                             +----------+
                      +-+--->| static a |
                      | |    +----------+
    +-----------+     | |
    |  ClassB   |     | |
    +-----------+     | |
    | (methods) |-use-+ |
    +-----------+       |
                        |
    +-----------+       |
    |  ClassC   |       |
    +-----------+       |
    | (methods) |-use---+
    +-----------+