What are class fields?#

Fields are variables defined within class code at the same level as methods. There are two fundamentally different categories for these fields: static and non-static fields.

  • Static fields are usually called class variables and their values are stored into Class instance representing the class code. Values of these variables are chared among all objects derived from the same Class object. See also A2AClassCastException for pitfalls to be aware of.
  • Non-static fields are usually called instance variables and their values are stored into the object itself.

How can I refer to fields?#

For a static fields you should always use the class name together with the actual field name so that there is a clear distinction between local instance and class instance allocations. Example: System.out

Instance variables can be refered by using prefixes this and super depending on their place or then you can use them with their plain name and the compiler will follow the standard visibility rules to figure out the correct variable.

Using explicit this is a bad habit, IMHO. More explanation on WhyUsingThisIsBad. --Janne

Can I use public fields?#

It is usually a good habit to hide all internal data structures of objects so that they can be changed with no effects to API. In addition the usage of guard methods gives us a change to write invariants and validations for the values.

Constants can be declared public fields since they cannot be modified and in most cases they are an essential part of the class API. This simplifies the code and speeds up things a lot.

I changed the value of my constant but the code is still using the old one.#

Java compilers tend to optimize code with static final variables by using inline copies in bytecode. As a result of this you will have to remove and recompile all classes files that are using the constant that you had modified.

Original author: Asser

Add new attachment

Only authorized users are allowed to upload new attachments.
« This page (revision-1) was last changed on 20-Jul-2001 03:09 by UnknownAuthor