3 · Object-Oriented Core · lesson 12 of 41

Classes & Objects

State + behavior packaged together.

Java
public class Point {
    double x, y;                    // fields (state)

    double distance(Point other) {  // method (behavior)
        double dx = x - other.x, dy = y - other.y;
        return Math.sqrt(dx*dx + dy*dy);
    }
}

Point p = new Point();  // 'new' allocates on the heap
p.x = 3; p.y = 4;
Loading 3D scene…
Key takeaways
  • ✓A class is a blueprint; an object is one instance in memory.
  • ✓'new' allocates a heap object and returns a reference.