CPSC 233 Tutorial Xin Mar 2, 2011
toString() method Add a toString() to a class to enable the print function public String toStinrg ( )
Example public class Foo { private int num; public Foo () { num = 0; } public Foo (int n) { setNum(n); } public int getNum () { return num; } public void setNum (int n) { num = n; } public String toString () { String temp = "Num="; temp = temp + num; return temp; } public boolean equals (Foo f) { return(this.num == f.num); } public class ReferenceDriver { public static void main (String [] args) { Foo f1; f1 = new Foo(10); System.out.println(f1); }
Deep copy vs. Shallow copy Deep copy Create a new object, and make it equal to the old one Shadow copy Just return the reference
Example public class MyCopy { public Foo shallowCopy (Foo aFoo) { Foo temp = aFoo; return temp; } public Foo deepCopy (Foo aFoo) { Foo temp = new Foo (); temp.setNum(aFoo.getNum()); return temp; } public class ReferenceDriver { public static void main (String [] args) { Foo f1; Foo f2; MyCopy aCopier = new MyCopy(); f1 = new Foo(10); f2 = aCopier.deepCopy(f1); f2.setNum(20); System.out.println(f1); System.out.println(f2); }
Static variables All objects share the same copy Can be used as “global” variables Use directly with class name eg. Mode.debug Even no objects are created
Static method Use with the class name eg. foo.max() don’t need to create an object although you can still use them with object name Static method access static attributes ✓ access non-static attributes ✗ attributes belong to objects call another static method ✓ call non-static class method ✗ using this reference ✗
Example class staticExample { public static int number = 1; public static int max (int n1, int n2) { if (n1 > n2) return n1; else return n2; } class staticExampleDriver { public static void main (String [] args) { int result = staticExample.max(1, 2); System.out.println("the result is " + result); result = staticExample.number; System.out.println("the result is " + result); staticExample eg = new staticExample(); result = eg.max(2, 3); System.out.println("the result is " + result); }
Read from a file import libraries import java.util.Scanner; import java.io.*; Open a file Scanner inputStream = new Scanner(new FileInputStream(“filename.txt”)); Read the file String line = inputStream.nextLine (); Close the file inputStream.close ();
Improve the grid program Initialize array from a txt file add tokens to random vacant space