Title: More Classes 3 : ReferencesParameters
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

MoreClasses-3 : References & Parameters

References to objects

1. Primitives and Classes work quite differently. Classes are accessed through addresses or References. In the following example we will discover that we can have more than one reference to the same Object. What you do to one reference affects the other reference as well. Just like anything that affects Clarence(my real name) affects Clem(my nickname). Consider the following sequence of code:




public class ToyClass
{
    private String name;
    private int number;

    public ToyClass(String initialName, int initialNumber)
    {
        name = initialName;
        number = initialNumber;
    }

    public void set(String newName, int newNumber)
    {
        name = newName;
        number = newNumber;
    }

    public String toString( )
    {
        return (name + " " + number);
    }

    public boolean equals(ToyClass otherObject)
    {
        return ( (name.equals(otherObject.name))
                  && (number == otherObject.number) );
    }

    public static void main(String[] args)
    {
        ToyClass t1 = new ToyClass("Red Truck", 1);
        ToyClass t2 = t1;
        t2.set("Barby Doll", 2);
        System.out.println(t1);
        // What output do we expect and why??
        if (t1 == t2)
            System.out.println("t1 and t2 are the same");
        ToyClass t3 = new ToyClass("Red Truck", 1);
        ToyClass t4 = new ToyClass("Barby Doll", 2);
        if (t1 == t3)
            System.out.println("t1 and t3 are the same");
        if (t1.equals(t3))
            System.out.println("t1 and t3 have the same contents");
        if (t4.equals(t1))
            System.out.println("t4 and t1 have the same contents");
    }

}

	
	

2. Parameter passing - If you understand the above, then the next step is to look at passing parameters for primitives and Objects. The basic rules are:

- Primitive parameters are passed as copies of values - which means that the called program cannot change the original
- Objects are passes as copies of addresses which normally means that the called program can change the contents of the object through the passed address(assumming the class is mutable ... i.e. it is modifiable)
- If the Object is immutable (it is not modifiable), then there is no way to change the contents of the object. The examples of immutable classes you will encounter are String, and the Wrapper classes (Integer, Double, etc.)


In the previous example, replace the main with the following main

        static void try2Modify(ToyClass t, int x, String s)
        {
            t.set("Big Bob", 3);
            x = 1000;
            s="Modified String";
        }
	
        public static void main(String[] args)
        {

            // The ToyClass is mutable
            ToyClass toy = new ToyClass("Red Truck", 1);
            int y=10;
            String s="Try to modify me"; // Strings are immutable

            try2Modify(toy, y, s);

            System.out.println("toy=" + toy);
            System.out.println("y="+y);
            System.out.println("s="+s);

        }

	

1. null - Special value that you can assign to any reference to indicate that your reference is currently unattached to any real object. If the compiler complains to you about initializing a reference variable, you can always use null to keep it happy.


	ToyClass t1; // Uninitialized variable (actually will default to null if no compile error occurs)
	ToyClass t1=null; // Properly initialized variable.  The t1 reference is currently unattached to any object.
	

2. Note that if a class is supposed to be passed to a method, the compiler will let you pass null. The method, however, must be prepared to handle the possibility of the its parameter having a null value. For example:
void someFunc(ToyClass tc) { ....

someFunc(null);
3. Special care for null - You cannot reference items in a class through a reference that contains null.


	String str = null;
	// The following statement will throw an exception and abort your program
	if (str.length() > 0)
	   System.out.println(" Chars exist");

// **************************************
	
	 class Data
	 {
	   int x=1;
	 };
	
	 Data d = null;
	 // The following statement will throw and exception and abort your program
	 System.out.println( d.x);
	

4. Anonymous Object -


  // Consider the following code, where temp is a variable that we don't intend to use again:

  ToyClass temp = new ToyClass("Joe", 42);
    if (variable1.equals(temp))
        System.out.println("Equal");
	
// An alternative Anonymous object (i.e. one that never has a real reference variable)
    if (variable1.equals( new ToyClass("Joe",42)    ))
        System.out.println("Equal");


Self Test Exercises:

1. When comparing 2 objects with ==, what are we actually checking for?
2. When using the equals method to compare 2 objects, what are we actually checking for?
3. When comparing 2 primitives (like int) with ==, what are we actually checking for?
4. Can a method with an argument of a class type change the address of the passed in object reference? ..... no, Go back and take a closer look at the try2Modify routine above.
5. Can a method with an argument of a class type change the contents of the object referenced in the parameter? .... yes
6. What is wrong with the program that starts as follows. This uses the ToyClass.java file.
ToyClass anObject = null;
anObject.set("Josephine", 42);
7. What is the type of the constant null? .... generic, or no type
8. Suppose aVariable is a variable of a class type. Which of the following correctly tests to see whether aVariable contains null?
aVariable.equals(null) .... no!
aVariable == null ..... good
9. Is the following legal in Java? The class ToyClass.java is referenced
System.out.println( new ToyClass("Mr. Cellophane", 0));
// we called this an anonymous class reference in the above notes

Properly handling References

1. Side Effects and Copy Constructors for Mutable Classes - Notice the side effects of changing the Mutable class Date in the example below. The Date class comes from the Author's code from chapter 5.

Switch to the alternative constructor of Person (switch the comments) to see how a copy constructor can resolve this issue.



public class Person {

    private String name;
    private Date born;

    public String toString()
    {
        return name + " born="+born.toString();
    }

    public Person (String name, Date born)
    {
        this.name = name;
        this.born = born;
    }

/*
 // Fixed version using a copy-constructor

    public Person (String name, Date born)
    {
        this.name = name;
        this.born = new Date(born); // Using Date copy constructor
    }
*/

    public static void main(String[] args) {
        Date d = new Date("April", 20, 1948);
        String name = "Clem";
        Person p = new Person(name, d);

        System.out.println(p);  // This calls p.toString()

        d.setYear(2013);
        name="Clarence";

        // Notice the side effect of changing the year
        // but no side effect for changing name
        System.out.println(p);

    }

}



2. Immutable classes - String , all wrapper classes (Integer, Double, Long, etc.) Consider the following:


public class Test {

    public static void main(String[] args) {
        String s1 ="abc";
        String s2 = s1;
        System.out.println(s1);
        s2 ="xyz";   // Note this does not impact s1

        // What is the output of the following
        System.out.println(s1);

        Integer x1 = 5;
        Integer x2 = x1;  // Automatic Boxing occurring
        System.out.println(x1);
        // The following does not impact x1
        x2 = 10;          // Automatic Boxing occurring
        System.out.println(x1);
    }
}
	
	

3. Mutable classes - What output is produced by the following code?


public class Test {

    public static void main(String[] args) {

          Date date1 = new Date("January", 1, 2006);
          Date date2;
          date2 = date1;
          date2.setDate("July", 4, 1776);
          System.out.println(date1);  // same as date2

          date1 = new Date("January", 1, 2006);
          Date date3;
          date3 = new Date(date1);  // using copy constructor
          date3.setDate("July", 4, 1776);
          System.out.println(date1); // date1 is unchanged by date3
    }
}



Java Practice(JPHP):

We want to list what happens when a calling method like main calls another method and passes a parameter. Assume that the called method modifies the parameter passed in. The question is what value does the variable have when the called method returns. What happens when:

1. (3 points) The parameter passed in is a primitive(int, double, char, boolean, etc). Write a short program to demo this.
2. (3 points) The parameter passed in is an immutable class(String, Integer, Double, other wrapper classes). Write a short program to demo this.
3. (4 points) The parameter passed in is a mutable class(Most classes). Write a short program to demo this. Create a simple Mutable class to demo use in your demo program.

Last Modified: December 6, 2014 2:47 PM