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

前端 未结 7 824
有刺的猬
有刺的猬 2020-12-05 04:49

I am starting studying OOP and I want to learn what constitutes a class. I am a little confused at how loosely some core elements are being used and thus adding to my confus

7条回答
  •  余生分开走
    2020-12-05 05:14

    "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 double 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.

提交回复
热议问题