Ojonugwa Jude Ochalifu
Ojonugwa Jude Ochalifu

Reputation: 27237

Why is it possible for objects to change the value of class variables?

By Oracle's definition,

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory.

By this definition, it is safe to deduce that a static variable belongs to the class and shouldn't be accessible for modification by any object of the class.Since all objects share it.

So this line from the same definition is a bit confusing:

Any object can change the value of a class variable...

So I tried this code and it prints 45 (although I get a warning saying "Static member accessed via instance reference"):

public class Main {

static int value = 8;

public static void main(String[] args) {
// write your code here

    Main main = new Main();

    main.value = 45;

    System.out.println(value);
  }
}

If this was a Student class, and I had a static variable called numberOfStudents, why should one object of that class be allowed to change the value of this class variable?

Upvotes: 2

Views: 6375

Answers (6)

Richard Chambers
Richard Chambers

Reputation: 17573

Being able to create a class with static variables and methods so that those variables and methods are shared by all instances or objects created from the class can be very useful, see When to use static methods.

When sharing a static variable in a class between multiple instances or objects created from the class, the synchronized modifier may be required in order to ensure that if the static variable is being modified by objects in more than one thread, that data integrity is maintained, see What does synchronized mean? and also see How to synchronize a static variable among threads running different instances of a class in java.

The final key word, see How final keyword works is used to determine whether a variable is immutable or not. So if you want to have a class static variable that should be immutable or a constant then you can add the final modifier to the definition. However see Java final keyword for variables which explains that the underlying value for a reference may not be immutable in the sense that functional programming means. See also what is meant by immutable as well as Why final keyword is necessary for immutable class.

You can also use modifiers such as public to determine the visibility of variables and methods in a class, see What does public static void mean in Java.

By using modifiers such as final or private the programmer is able to finely tune the visibility and modifiability of variables in class and objects instantiated from the class.

Upvotes: 4

Kazaag
Kazaag

Reputation: 2145

Litle example how the compiler change the object field access to a class field access.

public class A {
    static int foo = 25;

    static public void main(String[] arg){
        B b = new B();
        A a = b;

        System.out.println(b.foo);
        System.out.println(a.foo);
    }
}

class B extends A {
    static int foo = 60;
}

The output is:

60
25

It also shows that can be confiusing as it have different behaviour as for object fields.

Upvotes: 2

ArcaneEnforcer
ArcaneEnforcer

Reputation: 124

A static variable has a single instance for the whole class that defines it. When an instance is created, an instance of that static variable IS NOT CREATED. There is only one, and that one is freely modifiable by any function without the need for an instance. (unless it is declared final)

Upvotes: 0

Eng.Fouad
Eng.Fouad

Reputation: 117579

By this definition, it is safe to deduce that a static variable belongs to the class and shouldn't be accessible for modification by any object of the class.Since all objects share it.

No, static field is accessible for modifications, as long the access modifier allows it.


main.value = 45;

The compiler will read this line at compile-time as:

Main.value = 45;

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1499810

It's not really that "one object" can - it's just you're in code which has access to that variable, and unfortunately Java allows you to access static members (both variables and methods) as if they were instance members. This ends up with very misleading code, e.g.

Thread t = new Thread(...);
t.start();
t.sleep(1000);

The last line looks like it's asking the newly-started thread to sleep - but actually it'll make the current thread sleep.

This is basically a flaw in Java. The compiler will silently turn code like this into

Thread.sleep(1000);

or in your case

Main.value = 45;

(I believe that in an older version of Java, it would emit code that checked for nullity with the variable you were accessing the static member "through", but it doesn't even do that any more.)

Many IDEs will allow you to flag code like this with a warning or error. I would encourage you to turn on such a feature. If you see existing code like that, change it to use access the static member directly via the declaring class, so it's clear what's going on.

Upvotes: 11

StenSoft
StenSoft

Reputation: 9609

By this definition, it is safe to deduce that a static variable belongs to the class and shouldn't be accessible for modification by any object of the class.Since all objects share it.

No. By this definition, that static variable belongs to the class and is modifiable by any instance of the class. There is no implication that when some variable is shared that it should not be modifiable. Use final if you want that.

If this was a Student class, and I had a static variable called numberOfStudents, why should one object of that class be allowed to change the value of this class variable?

To increment the value in constructor and decrement it in finalizer, for example.

Upvotes: 0

Related Questions