Bala
Bala

Reputation: 11264

Can an instance of a class modify static / class variable?

class Person {
  public static int age = 10;
}

public class Application {
  public static void main(String[] args) {

    Person p = new Person();
    p.age = 100;
    System.out.println(Person.age);

    Person.age = 22;
    System.out.println(p.age);
  }
}

I got 100 and 22 printed. Was I wrong in assuming that instances of a class cannot access/modify class/static variables.

Upvotes: 0

Views: 2466

Answers (3)

Mark W
Mark W

Reputation: 2803

I think the part your confused by is the meaning of static. the age variable in class Person will be shared across all instances of Person, and can be accessed with no instance at all via:

Person.age = 100;

Changing it for any instance:

Person p = new Person();   
p.age = 100;

changes it for everyone, and is the same as calling

Person.age = 100;

Changing it in a non static way, meaning via some instance only makes the code misleading by making people think they are changing an instance variable at first glance. You will get a compiler warning about this.

Upvotes: 1

Mena
Mena

Reputation: 48434

Of course an instance of a class can access and modify a static field, if it's accessible to that scope.

What cannot happen is a static statement/method body modifying an instance it does not "know about", e.g. a static method using this.

Example

public class Main {
    private static int meh = 0;
    int blah = 0;
    public static void main(String[] args) {
        // ugly but compiles fine
        // equivalent to Main.meh = 1
        meh = 1;
        // Will NOT compile - main method is static, 
        // references instance field "blah" out of scope
        // Equivalent to this.blah = 1
        blah = 1;
    }
}

Upvotes: 1

nikis
nikis

Reputation: 11244

Yes, they can. From the docs:

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. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class

Upvotes: 1

Related Questions