Compare objects in Java to cloud-hosted documents, such as Google Docs, for a relatable analogy to explain object references with.

  • This comparison is useful because students may already have experience with cloud storage like Google Docs.
  • The comparison works as follows:
    • If a student makes a copy of a Google Doc, any changes made in the original will not appear in the copy (and likewise any changes made to the copy will not appear in the original document). This is analogous to making a deep copy, which is creating a new object with all of the same values and properties as the original.
    • On the other hand, if a Google Doc is shared, then any changes made to the original will show in the Google Doc for everyone, since all people are using the same object when they’re contributing changes. This is analogous to making a shallow copy, in which a new object references the original object, so that any changes to either object affect both objects.
  • Consider the following Java code from the 2009 AP CS A exam multiple choice that demonstrates making a shallow copy:
      public class SomeClass {
        private int num; public SomeClass(int n) {
          num = n;
        } public void increment(int more) {
          num = num + more;
        } public int getNum() {
          return num;
        }
      } SomeClass one = new SomeClass(100); SomeClass two = new SomeClass(100); SomeClass three = one; one.increment(200); System.out.println(one.getNum() + " " + two.getNum() + " " + three.getNum());
    • In order to resolve what gets printed, students must understand that the line "SomeClass three = one" is analogous to sharing a Google Doc.

More about this tip

External Source
Leigh Ann Sudol-DeLyser’s notes from 2009 AP CS A exam.