Polymorphism

The practice of providing a single interface entities of different types can interact with. In Java, this is implemented in objects with subtypes, where any variable is declared of a static type, but its behavior is based on its dynamic type.

Dynamic type is what an object is considered at runtime, after it is instantiated, and is always a subtype of the static type (i.e. “it is a kind of” that type). Static type is what an object is considered at compile time.

Dynamic type is what an object is considered at runtime, after it is instantiated, and is always a subtype of the static type (i.e. “it is a kind of” that type). Static type is what an object is considered at compile time.


Comparable

Widely used, built-in interface that specifies a compareTo method, which defines a natural order to objects within a class. This method is implemented within the same class.

public interface Comparable<T> {
		public int compareTo(T obj);
}

Comparator

Interface which specifies a compare method, which defines an external order to objects within a class. This method is implemented within another class.

import java.util.Comparator;

public interface Comparator<T> {
		public int compare(T o1, T o2);
}
private class typeComparator implements Comparator<T> {
		public int compare(T a, T b) {
				// ...
		}
		
		public static Comparator<T> getComparator() {
				return new typeComparator();
		}
}

Iterables

Any data structure which can be iterated over with an enhanced for loop must implement Iterable, which requires a valid iterator method to be implemented.

public interface Iterable<T> {
		public Iterator<T> iterator();
}

The following 2 code blocks are the same.

for (T e : struct) {
		// ...
}
Iterator<T> seer = struct.iterator();
while (seer.hasNext()) {
		T e = seer.next();
		// ...
}

Iterator