Print Page Print Page

CH10 – Aliasing

  1. Create a new class named Aliasing.
  2. Add a new method named printBoxes that takes two Rectangles as parameters and contains the following code. Don’t forget to import the java.awt.Rectangle class.
import java.awt.Rectangle;
public class Aliasing {
  public static void printBoxes(Rectangle box1, Rectangle box2){
    System.out.println(box1.hashCode());
    System.out.println(box2.hashCode());
    System.out.println(box1.toString());
    System.out.println(box2.toString());
  }
}
  1. Add a main method with the following code.
public static void main(String[] args){
  Rectangle a = new Rectangle(0,0,100,200);
  Rectangle b = a;
  printBoxes(a, b);
}
  1. Compile and run the program.
$ javac Aliasing.java
$ java Aliasing
-1573257216
-1573257216
java.awt.Rectangle[x=0,y=0,width=100,height=200]
java.awt.Rectangle[x=0,y=0,width=100,height=200]

The complete class should appear as follows.

import java.awt.Rectangle;
public class Aliasing {
  public static void main(String[] args){
    Rectangle a = new Rectangle(0,0,100,200);
    Rectangle b = a;
    printBoxes(a, b);
  }
  public static void printBoxes(Rectangle box1, Rectangle box2){
    System.out.println(box1.hashCode());
    System.out.println(box2.hashCode());
    System.out.println(box1.toString());
    System.out.println(box2.toString());
  }
}