OOP Terminology: class, attribute, property, field, data member

“Fields”, “class variables”, and “attributes” are more-or-less the same – a low-level storage slot attached to an object. Each language’s documentation might use a different term consistently, but most actual programmers use them interchangeably. (However, this also means some of the terms can be ambiguous, like “class variable” – which can be interpreted as “a variable of an instance of a given class”, or “a variable of the class object itself” in a language where class objects are something you can manipulate directly.)

“Properties” are, in most languages I use, something else entirely – they’re a way to attach custom behaviour to reading / writing a field. (Or to replace it.)

So in Java, the canonical example would be:

class Circle {

    // The radius field
    private double radius;
    public Circle(double radius) {
        this.radius = radius;
    }

    // The radius property
    public double getRadius() {
        return radius;
    }
    public void setRadius(double radius) {
        // We're doing something else besides setting the field value in the 
        // property setter
        System.out.println("Setting radius to " + radius);
        this.radius = radius;
    }

    // The circumference property, which is read-only
    public double getCircumference() {
        // We're not even reading a field here.
        return 2 * Math.PI * radius;
    }

}

(Note that in Java, a property foo is a pair of accessor methods called getFoo() and setFoo() – or just the getter if the property is read-only.)


Another way of looking at this is that “properties” are an abstraction – a promise by an object to allow callers to get or set a piece of data. While “fields” etc. are one possible implementation of this abstraction. The values for getRadius() or getCircumference() in the above example could be stored directly, or they could be calculated, it doesn’t matter to the caller; the setters might or might not have side effects; it doesn’t matter to the caller.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)