0

I'm new in Java and help me please

public class Student {
    
    static int status = 10;
}


Student person = new Student(5, 78);



System.out.println(person.status);// why static props is work here ?

Emample 2

 Student person = new Student(5, 78);
 Student person2 = new Student(15, 10);
  
 person.status = 66;

 System.out.println(Student.status);
 System.out.println(person.status);
 System.out.println(person2.status); // WOW !
 System.out.println(Student.status); // WOW !

I expected Unexpected error here . Exception! Why in java static fields works for object ?

zloctb
  • 10,592
  • 8
  • 70
  • 89
  • 1
    the Java field can be declared static. In Java, static fields belongs to the class, not instances of the class. Thus, all instances of any class will access the same static field variable. A non-static field value can be different for every object (instance) of a class. ... http://tutorials.jenkov.com/java/fields.html – Huy Nguyen Nov 25 '21 at 06:43

1 Answers1

1

Static fields in Java classes can be a bit confusing if you haven't used the concept before. Specifically, the static field is associated with the class, not the object. This means that your status field belongs to the class of Student, not to any of the individual objects that instantiate Student. Because of this, the correct way to access status is via the class: Student.status. All instances of Student (such as person and person2) have access to that static field, but they all share the same field (since it actually belongs to the class), so any changes will be reflected for all of them!

This also means you can access static fields without ever instantiating the class! Student.status will work even if you have never called new Student() anywhere in your code. For example, the Math class in the standard library has static fields for things like pi: Math.pi works, even though you never created an instance of Math.

You can find plenty more explanations of static fields in Java if my answer doesn't explain the concept fully!

RedBassett
  • 3,469
  • 3
  • 32
  • 56