Java Interface
public interface Displaceable {
public int getX ();
public int getY ();
public void move(int dx, int dy);
}
public class Point implements Displaceable {
private int x, y;
public Point(int x0, int y0) {
x = x0;
y = y0;
}
public int getX() { return x; }
public int getY() { return y; }
public void move(int dx, int dy) {
x = x + dx;
y = y + dy;
}
}
class ColorPoint implements Displaceable {
private Point p;
private Color c;
ColorPoint (int x0, int y0, Color c0) {
p = new Point(x0,y0);
c = c0;
}
public void move(int dx, int dy) {
p.move(dx, dy);
}
public int getX() { return p.getX(); }
public int getY() { return p.getY(); }
public Color getColor() { return c; }
}
// This methods will work on an object created from any class with the interface
public void moveItALot(Displaceable s) {
s.move(3,3);
s.move(100, 1000);
s.move(s.getX(), s.getY());
}
Core Java
int // standard integers
byte, short, long // other flavors of integers
char // unicode characters
float, double // floating-point numbers
boolean
== // reference equality
a.equals(b) // structural equality
Static vs. Dynamic Methods
a dynamic property of the program—itsbehavior can’t be determined until the program is actually running
As the use of the keyword static implies, which code is called when a static method is invoked can be determined at compile time (without running the program). The way this works is that, rather than invoking a static method from an object, static methods are called relative to the class in which they are defined.
When should static methods be used? Generally they should be used for implementing functions that don’t depend on any objects’ states
Array
int [] arr = new Counter[10]
int[] myArray = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
String[] yourArray = { "foo", "bar", "baz" };
Point[] herArray = { new Point(1,3), new Point(5,4) };
Because array elements are mutable, all of the issues with aliasing (recall §14) arise here as well.
public static double sum(double[] arr) {
double total = 0;
for (int i = 0; i < arr.length; i++) {
total = total + arr[i];
}
}
public static double sum(double[] arr) {
double total = 0;
int i = 0; // loop index initialization
while (i < arr.length) { // loop guard
total = total + arr[i];
i++; // loop index update
}
}
Multi-dimensional array isn’t neccessary to be a rectangle
String[][] names = {{"Mr. ", "Mrs. ", "Ms. "},
{"Smith", "Jones"}};
for (int r=0; r < arr.length; r++){
// use the length of the inner array
for (int c=0; c < arr[r].length; c++) {
arr[r][c] = ...
}
}
int[][] products = new int[5][];
for(int row = 0; row < 5; row++) {
products[row] = new int[row+1];
for(int col = 0; col <= row; col++) {
products[row][col] = row * col;
}
}