Java Objects

intermediate40 min

Objects

An object is one instance of a class. Use new and a constructor to create it. Each object has its own field values but uses the same methods defined on the class.

Creating objects

Object State and Behavior

State lives in instance variables; behavior is the shared methods on the class.

Multiple objects

Understanding Object References

Object variables hold references (addresses), not the object itself. Two variables can refer to the same object; updates through either name show up on both.

References example

Reference rules

  • Variables hold references, not embedded objects
  • Several variables can point at one object
  • null means no object
  • == compares references; .equals() compares content (when implemented)
  • Changes through any reference affect the same object

Objects as parameters

Methods receive a copy of the reference. The method can change the object’s fields; those changes remain visible after the call.

Parameters example