class Counter(object):
"""Return ascending integers
"""
def count(self):
"""Return next integer
"""
self.counter = self.counter + 1
return self.counter
def __init__(self):
self.counter = -1
class CounterTestCase(TestCase):
def test_starts_from_zero(self):
c = Counter()
self.assertEqual(c.count(), 0)
def test_increments(self):
c = Counter()
c.count()
self.assertEqual(c.count(), 1)
def test_separate_instances(self):
a = Counter()
b = Counter()
a.count()
self.assertEqual(a.count(), 1)
self.assertEqual(b.count(), 0)
Subtyping polymorphism
static void printSeries(Iterable<BigInteger> series) {
for (BigInteger i : series)
System.out.println(i);
}
class FibonacciIterator implements Iterator<BigInteger> {
public boolean hasNext() { return true; }
public BigInteger next() { /* ... */ }
}
Subtyping polymorphism
abstract class Shape {
public abstract double area();
@Override public String toString() {
return "Shape area=" + area();
}
}
class Circle extends Shape {
private double radius;
@Override public double area() {
return 2 * Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private double height, width;
@Override public double area() {
return height * width;
}
Parametric polymorphism
class IterableDisplayer<T> {
Iterable<T> series;
IterableDisplayer(Iterable<T> s) { series = s; }
void printSeries() {
for (T i : series)
System.out.println(i);
}
}
Ad hoc polymorphism
public class SimpleMath {
static double atan(double y, double x) {
return Math.atan2(y, x);
}
static double atan(double v) {
return Math.atan(v);
}
}