100 likes | 200 Views
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 ); }
E N D
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 (intn) { setNum(n); } public intgetNum () { return num; } public void setNum (intn) { num = n; } public String toString () { String temp = "Num="; temp = temp + num; return temp; } public boolean equals (Foof) { return(this.num == f.num); } } public class ReferenceDriver { public static void main (String [] args) { Foof1; 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 FooshallowCopy (FooaFoo) { Foo temp = aFoo; return temp; } public FoodeepCopy (FooaFoo) { Foo temp = new Foo (); temp.setNum(aFoo.getNum()); return temp; } } public class ReferenceDriver { public static void main (String [] args) { Foo f1; Foo f2; MyCopyaCopier = 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 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); staticExampleeg = new staticExample(); result = eg.max(2, 3); System.out.println("the result is " + result); } } class staticExample { public static int number = 1; public static int max (int n1, int n2) { if (n1 > n2) return n1; else return n2; } }
Read from a file • import libraries • import java.util.Scanner; • import java.io.*; • Open a file • Scanner inputStream = new Scanner(newFileInputStream(“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