Fundamentals

Object-oriented programming’s roots date back several decades to languages such as Simula and Smalltalk. OOP has been the subject of much academic research and debate, especially since the widespread adoption of OOP languages by practicing developers.

Classes and Objects

There are many different ways and no clear consensus on how to describe and define object orientation as a programming technique, but all of them revolve around the notions of classes and objects. A class is an abstract definition of something that has attributes (sometimes called properties or states) and actions (capabilities or methods). An object is a specific instance of a class that has its own state separate from any other object instance. Here’s a class definition for Point, which is a pair of integers that represents the x and y values of a point in a Cartesian coordinate system:

public class Point {
    private int x;
    private int y;
    public Point( int x, int y ){
        this.x = x;
        this.y = y;
    }
    public Point( Point other ){
        x = other.getX();
        y = other.getY();
    }
    public int getX(){ return x; }
    public int getY(){ return y; }
    public Point relativeTo( int dx, int dy ){
        return new Point( x + dx, y + dy ); 
    }
    public String toString(){
        StringBuffer b = new StringBuffer();
        b.append( '(' );
        b.append( x );
        b.append( ',' );
        b.append( y );
        b.append( ')' );
        return b.toString();
    }
}

To represent a specific point, simply create an instance of the Point class with the appropriate values:

Point p1 = new Point( 5, 10 ); ...

Get Programming Interviews Exposed: Secrets to Landing Your Next Job, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.