Session 23 Chapter 11: More on the Implications of Inheritance Stack-based Memory Main: ObjA a = new ObjA(); ObjB b = new ObjB(); a.do(5, b) public class ObjA { int x = 100; public void do (int y, ObjB myB) { int loc = 6; int t = myB.doMore(loc); ... } public class ObjB { int z = 30; public int doMore(int i) { z = z + i; return z; } } } • Objects are stored on the heap • When a method is called, an activation record is allocated on the stack to hold: – return address (where to return after execution) – parameters – local variables (stuff declared in the method) • When a method returns, the activation record is popped Consider Factorial Example class FacTest { static public void main (String [] args) { int f = factorial(3); // * System.out.println(“Factorial of 3 is “ + f); } static public int factorial (int n) { int c = n – 1; int r; if (c > 0) { r = n * factorial(c); } else { r = 1; } return r; } } // ** Assignment of Objects • semantics for assignment simply copies the pointer into the heap to the object public class Box { pubic class BoxTest { public static void main (String [] args) { private int value; public Box() { value = 0; } Box x = new Box(); public void setValue (int v) { x.setValue ( 7 ); Box y = x; value = v; } y.setValue( 11 ); public int getValue() { System.out.println( “x’s value = “ + x.getValue()); System.out.println(“y’s value = “ + y.getValue()); return value; } // end main } } } Cloneable Interface • Java has no general mechanism to copy arbitrary objects • But, the base class Object provides a clone() method that creates a bitwise copy • The Cloneable interface represents objects that can be cloned • Several methods in Java’s library use clone() Cloneable Box Class public class Box implements Clonable { private int value; public Box() { value = 0; } public void setValue (int v) { value = v; public int getValue() { return value; } public Object clone() { Box b = new Box(); b.setValue ( getValue()); return b; } // end clone } } Using the Cloneable Box Class pubic class BoxTest { public static void main (String [] args) { Box x = new Box(); x.setValue ( 7 ); Box y = (Box) x.clone(); y.setValue( 11 ); // assigns y a copy of y System.out.println( “x’s value = “ + x.getValue()); System.out.println(“y’s value = “ + y.getValue()); } // end main } Equality Test • == tests for pointer equality, so == really tests for object identity and not equality. • equals() is a method inherited from class Object. The Java run-time system uses equals() in a number of places and expects to be able to test any Object for equality with any other Object. Equality Test Example class Circle extends Shape { int radius; ... int getRadius() { return radius; } ... public boolean equals (Object arg) { if (arg instanceof Circle) { Circle argc = (Circle) arg; if (radius == argc.getRadius()) { return true; } // end if } // end if return false; } }