Static vs. Instance Data Fields
- Static (or class) data fields
- Unique to the entire class
- Shared by all instances (objects) of that class
-
Accessible using
ClassName.fieldName
- The class name is optional within static and instance methods of the class, unless a local variable of the same name exists in that scope
- Subject to the declared access mode, accessible from outside the class using the same syntax
- Instance (object) data fields
- Unique to each instance (object) of that class (that is, each object has its own set of instance fields)
-
Accessible within instance methods and constructors using
this.
fieldName
-
The
this.
qualifier is optional, unless a local variable of the same name exists in that scope -
Subject to the declared access mode, accessible from outside the class from an object reference using
objectRef.fieldName
static int vacationDays = 10;and we print this in the Employee’s
print()
method:System.out.println("Vacation Days: " + vacationDays);In the EmployeeDemo’s
main()
method, we change vacationDays
to 15:Employee.vacationDays = 15;Now,
e1.print()
and e2.print()
will both show the vacation days set to 15. This is because both e1
and e2
(and any other Employee object) share the static vacationDays
integer field.The field
vacationDays
is part of the Employee class, and this is also stored on the heap, where it is shared by all objects of that class.Static fields that are not protected (which we will soon learn how to do) are almost like global variables — accessible to anyone.
Note that it is possible to access static fields through instance variables (e.g.,
e1.vacationDays = 15;
will have the same effect), however this is discouraged. You should always access static fields by ClassName.staticFieldName
, unless you are within the same class, in which case you can just say staticFieldName
.
No comments:
Post a Comment