Skip to content

Instantly share code, notes, and snippets.

@iande
Created April 10, 2012 13:45
Show Gist options
  • Save iande/2351488 to your computer and use it in GitHub Desktop.
Save iande/2351488 to your computer and use it in GitHub Desktop.
Rectangle Example
public interface Logger {
public void debug(String msg);
public void info(String msg);
public void warn(String msg);
public void error(String msg);
public void fatal(String msg);
}
public class Rectangle {
public static int COUNTER = 0;
public int width;
public int height;
private int myX;
private int myY;
public Rectangle(int x, int y, int w, int h) {
// Position and dimensions were given, so we construct a rectangle at (x,y)
// with a width of w, and a height of h.
myX = x;
myY = y;
width = w;
height = h;
Rectangle.COUNTER += 1;
}
public Rectangle(int w, int h) {
// Width and height were given, so we construct a rectangle at (0,0)
// with a width of w, and a height of h.
this(0, 0, w, h);
// The previous line tells the JVM to use a constructor that takes
// 4 integral arguments and uses the given width and height.
}
public Rectangle() {
// No arguments were given, so we construct a rectangle at (0,0)
// with a width of 0, and a height of 0. (The zero's are the default
// values.)
this(0, 0, 0, 0);
// The previous line tells the JVM to use a constructor that takes
// 4 integral arguments.
}
public int getX() {
return myX;
}
public int getY() {
return myY;
}
public int getArea() {
return width * height;
}
public void setX(int x) {
myX = x;
}
public void setY(int y) {
myY = y;
}
public void move(int x, int y) {
myX = x;
myY = y;
// or, we could replace the previous 2 lines with:
// setX(x);
// setY(y);
}
}
public void anExampleOfCasting() {
Object arr[] = new Object[3];
arr[0] = "Hello!";
arr[1] = new Integer(5);
arr[2] = "World!";
String myString = arr[0];
// That line will generate a compile time error, because Java sees
// every element in the array `arr` as an instance of Object. So, even
// though `arr[0]` really is an instance of String, we have to typecast
// it to use it as one:
String myString = (String)arr[0];
}
public void someMethod() {
Rectangle rect = new Rectangle(0, 0, 5, 10); // centered at (0,0), width is 5, height is 10
rect.move(3, 4);
int xPos = rect.getX();
int yPos = rect.getY();
// 1) xPos == ?
// 2) yPos == ?
rect.move(-10, 8);
int xPos2 = rect.getX();
int yPos2 = rect.getY();
// 3) xPos2 == ?
// 4) yPos2 == ?
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment