In a Java class, what are fields and methods?
Options
- Fields store the object's state; methods define its behavior (Correct option)
- Fields are functions; methods are variables
- Fields run the program; methods are only comments
- They are the same thing, just named differently
Answer
Fields store the object's state (data); methods define its behavior (actions)
Why
The Java tutorial: an object stores its state in fields and exposes its behavior through methods.
Example: for a Bicycle, the fields are speed and gear; the methods are speedUp() and changeGear().
Methods work on the object's fields. Keeping fields private and using methods to change them is called encapsulation.
Remember
Fields = data. Methods = actions.