Pregunta

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 ?

¿Fue útil?

Solución

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---+
+-----------+

Otros consejos

Static fields are relevant to the class and not the instance. A modification to a static field will cause all references to that field to return the last value assigned. In a sense, A is now defined as a global variable within your application, under most use cases this is not consider a good thing.

public class App {

    public static void main(String[] args) {
        B b = new B();
        C c = new C();

        System.out.println(A.a); //outputs 10
        b.changeA();
        System.out.println(A.a); //outputs 30
        c.changeA();
        System.out.println(A.a); //outputs 20
    }
}

class A{
    static int a = 10;
}

class B{
    public void changeA(){
        A.a = 30;
    }
}

class C{
    public void changeA(){
        A.a = 20;
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top