3.6 Methods: Passing and Returning References of an Object

19 阅读1分钟

1. Exam Points

  • Pass the an object as a parameter into a method.
  • Return an object as a returned value from a method.
  • For a reference type (mutable) parameter, changes to the parameter will reflect on the object passed to the parameter. But String is an exception, since String is an immutable class.
  • Methods from external classes can not access private instance variables or methods of a reference type parameter.
  • Methods from internal classes can access private instance variables or methods of a reference type parameter

2. Knowledge Points

(1) Methods: Passing and Returning References of an Object

  • When an argument is an object reference, the parameter is initialized with a copy of that reference; it does not create a new independent copy of the object. image.png
    • In this example, x and y refer to the same object, only one object is created using the new keyword.
  • If the parameter refers to a mutable object (String is immutable), the method or constructor can use this reference to alter the state of the object. image.png
    • In this example, the age of the dog is changed since we pass dog1(an object) to d.
  • When the return expression evaluates to an object reference, the reference is returned, not a reference to a new copy of the object. image.png

(2) Access private instance variables or methods

  • Methods cannot access the private data and methods of a parameter that holds a reference to an object unless the parameter is the same type as the method’s enclosing class. image.png
    • In this example, since age is private, so it can not be accessed using the parameter x.

3. Exercises