// INHERIT8: demonstrate how $super$ can help classes set instance variables // Calling $super$ means calling a constructor in a superclass. // But, any values that Java sets occur in the subclass. public class inherit8 { public static void main(String args[]) { Data1 d1 = new Data1(1); System.out.println(d1.m); // Output: 1 // Does $Data2$ "store" a value in $Data1$'s instance variable $m$? // Create a $Data2$ object: Data2 d2 = new Data2(2); // Now check the $Data1$ object referred to by $d1$: System.out.println(d1.m); // Output: 1 // Creating a $Data1$ object does not affect the $Data2$ object. // $d1$ and $d2$ refer to entirely different objects! // When $d2$ calls $super$, the value 2 is passed to a $Data1$ // constructor, which assigns the value 2 to instance variable // $m$ inside $Data2$. Why? $Data2$ inherits $m$. // So, The value of $m$ inside the object referred by $d2$ // should be 2: System.out.println(d2.m); // Output: 2 } } class Data1 { int m; Data1(int m) { this.m = m; } } // class Data1 class Data2 extends Data1 { Data2(int m) { super(m); } } // class Data2 /* output: 1 1 2 */