// expanding on concepts from IV1 and IV2 examples //----------------------------------------------------------------------------- // Do instance variables have to be written before methods? // No. So, what happens when you create a class? // Java assigns instance variables in the order that they're written. // Then, Java performs tasks inside the constructor that you called. public class iv3 { public static void main(String[] args) { Test1 t1 = new Test1(1,2); Test2 t2 = new Test2(3,4); } } class Test2 { // constructor first Test2(int x, int y) { print("Test 2 (1): "); this.x=x; this.y=y; print("Test 2 (2): "); } // instance variables next int x; int y=x; // instance method: print out IV values void print(String s) { System.out.println(s + this.x); System.out.println(s + this.y); } } class Test1 { // instance variables first int x; int y=x; // constructor next Test1(int x, int y) { print("Test 1 (1): "); this.x=x; this.y=y; print("Test 1 (2): "); } // instance method: print out IV values void print(String s) { System.out.println(s + this.x); System.out.println(s + this.y); } } // Output // In both cases, the IVs are assigned in order. // Then code statements inside the constructors are called. /* output: Test 1 (1): 0 // before constructor assigns value Test 1 (1): 0 // before constructor assigns value Test 1 (2): 1 // after constructor assigns value Test 1 (2): 2 // after constructor assigns value Test 2 (1): 0 Test 2 (1): 0 Test 2 (2): 3 Test 2 (2): 4 */