Rishi Jain
Rishi Jain

Reputation: 11

Doesn't this defy the rules of static variables?

I have declared a static variable and am changing its value through a non-static method by invoking it in the Initializer block which will be invoked every time an object is instantiated. Why does this not give me run time or compile time error?

public class FinalKeyWord {

    final int age;
    static int name;

    {
        ran();
        displayName();
    }


    public FinalKeyWord() {
        this.age = 10;
    }

    public FinalKeyWord(int a){
        this.age = a;
    }

    void ran(){
        Random r = new Random();
        int rand = r.nextInt(6);
        System.out.println(rand);
        name = rand;
    }

    public void displayAge() {
        System.out.println("This is final " + age);
    }

    public void displayName() {
        System.out.println("This is static " + name);
    }

    public static void main(String[] args) {

        FinalKeyWord a = new FinalKeyWord();
        //a.displayAge();
        //a.displayName();
        FinalKeyWord a2 = new FinalKeyWord(35);
        //a2.displayName();

    }

}

Output:

    This is static 2 \n
    This is is static 3

Upvotes: 0

Views: 73

Answers (2)

amm965
amm965

Reputation: 459

a variable being static doesn't mean that you can't change its value later, it means that its allocated once in memory for all instances of the class its in, so whenever you create an new object it will point to the same block in memory for this variable unlike normal variables or instance variables where a new block in memory will be reserved for this variable whenever a new object of this class is created.

Upvotes: 1

dSanders
dSanders

Reputation: 165

From Java Documentation/Tutorials,

Instance methods can access class variables and class methods directly.
So this is perfectly legal,

public class FinalKeyWord {

    static int a = 5;

    void change() {
        a= 10;
    }

    public static void main(String[] args) {
        FinalKeyWord obj = new FinalKeyWord();
        System.out.println(a);
        obj.change();
        System.out.println(a);
    }
}

And will print,

5
10

Upvotes: 0

Related Questions