They are essentially the global variables of a class meaning that they can be used in all constructors and methods in the class, and other classes if the field is public. If it is private then a accessor method needs to be used in order to get the value of the field. Normally a field will be different depending on the object that you call, this is because a objects constructor often changes the value of the field, since those fields are specific to the object , for example say you made two Square objects. The length width and side for those two rectangles/squares will probably be different, so it doesn’t make sense for the length and , width variables to carry over from one object to the next.
A regular public field is called by doing:
objectName.fieldName
The only time that a field stays the same no matter the object is when the field is static. This is because the reserved word static makes it so the field applies to all objects at the same time.You would use static if you were trying to get something like a total or a statistic of all of the objects of the class.
A public static field is called by doing:
className.fieldName
A Field is declared in the body of a class outside of constructors or methods and is generally at the very top right under the brace after the class declaration.
The format for a field declaration is:
public(or private) (static) data type field Name (= value of datatype) ;
One thought on “Fields”
Comments are closed.