0
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.

3
  • 1
    What do you mean by an "instance variable modifying a static variable"? How can a variable modify another? Also, just think about it -- it's the other direction that doesn't make sense (i. e. static methods cannot possibly access instance variables). Why would the other direction be prohibited? Commented Apr 22, 2014 at 18:08
  • You are right, I have modified it to instance of a class. Commented Apr 22, 2014 at 18:09
  • I have no idea what the code you've posted is designed to demonstrate. Commented Apr 22, 2014 at 18:10

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.