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

前端 未结 7 734
有刺的猬
有刺的猬 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:10

    In The Class

    public class ClassSample
    {
        private int ClassAttribute;
    
        public int Property
        {
            get { return ClassAttribute; }
            set { ClassAttribute = value; }
        }
    }
    

    In the Program

        class Program
        {
            static void Main(string[] args)
            {
                var objectSample = new ClassSample();
                //Get Object Property
                var GetProperty = objectSample.Property;
            }
        }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-05 05:16

    I've been doing oop for more than 20 years, and I find that people often use different words for the same things. My understanding is that fields, class variables and attributes all mean the same thing. However, property is best described by the stackoverflow link that you included in your question.

    0 讨论(0)
  • 2020-12-05 05:26

    Generally fields, methods, static methods, properties, attributes and class (or static variables) do not change on a language basis... Although the syntax will probably change on a per language basis, they will be function in the way you would expect across languages (expect terms like fields/data members to be used interchangably across languages)

    In C#....

    A field is a variable that exists for a given instance of a class.

    eg.

    public class BaseClass
    {
        // This is a field that might be different in each instance of a class
        private int _field; 
    
        // This is a property that accesses a field
        protected int GetField
        {
            get
            {
                return _field;
            }
        }
    }
    

    Fields have a "visibility" this determines what other classes can see the field, so in the above example a private field can only be used by the class that contains it, but the property accessor provides readonly access to the field by subclasses.

    A property lets you get (sometimes called an accessor) or set (sometimes called a mutator) the value of field... Properties let you do a couple of things, prevent writing a field for example from outside the class, change the visibility of the field (eg private/protected/public). A mutator allows you to provide some custom logic before setting the value of a field

    So properties are more like methods to get/set the value of a field but provide more functionality

    eg.

    public class BaseClass
    {
        // This is a field that might be different in each instance of a class
        private int _field; 
    
        // This is a property that accesses a field, but since it's visibility 
        // is protected only subclasses will know about this property 
        // (and through it the field) - The field and property in this case
        // will be hidden from other classes.
        protected int GetField
        {
            // This is an accessor
            get
            {
                return _field;
            }
            // This is a mutator
            set
            {
                // This can perform some more logic
                if (_field != value) 
                {
                     Console.WriteLine("The value of _field changed");
                     _field = value;
                     OnChanged; // Call some imaginary OnChange method
                } else {
                     Console.WriteLine("The value of _field was not changed");
                }
            }
        }
    }
    

    A class or static variable is a variable which is the same for all instances of a class.. So, for example, if you wanted a description for a class that description would be the same for all instance of the class and could be accessed by using the class eg.

    public class BaseClass
    {
        // A static (or class variable) can be accessed from anywhere by writing
        // BaseClass.DESCRIPTION
        public static string DESCRIPTION = "BaseClass";
    }
    
    public class TestClass
    {
        public void Test()
        {
            string BaseClassDescription = BaseClass.DESCRIPTION;
        }
    }
    

    I'd be careful when using terminology relating to an attribute. In C# it is a class that can be applied to other classes or methods by "decorating" the class or method, in other context's it may simply refer to a field that a class contains.

    // The functionality of this attribute will be documented somewhere
    [Test]
    public class TestClass
    {
        [TestMethod]
        public void TestMethod()
        {
        }
    }
    

    Some languages do not have "Attributes" like C# does (see above)

    Hopefully that all makes sense... Don't want to overload you!

    0 讨论(0)
  • 2020-12-05 05:29

    I agree with you, there's a lot of unnecessary confusion due to the loose definitions and inconsistent use of many OO terms. The terms you're asking about are used somewhat interchangeably, but one could say some are more general than others (descending order): Property -> Attributes -> Class Variables -> Fields.

    The following passages, extracted from "Object-Oriented Analysis and Design" by Grady Booch help clarify the subject. Firstly, it's important to understand the concept of state:

    The state of an object encompasses all of the (usually static) properties of the object plus the current (usually dynamic) values of each of these properties. By properties, we mean the totality of the object's attributes and relationships with other objects.

    OOP is quite generic regarding certain nomenclature, as it varies wildly from language to language:

    The terms field (Object Pascal), instance variable (Smalltalk), member object (C++), and slot (CLOS) are interchangeable, meaning a repository for part of the state of an object. Collectively, they constitute the object's structure.

    But the notation introduced by the author is precise:

    An attribute denotes a part of an aggregate object, and so is used during analysis as well as design to express a singular property of the class. Using the language-independent syntax, an attribute may have a name, a class, or both, and optionally a default expression: A:C=E.

    Class variable: Part of the state of a class. Collectively, the class variables of a class constitute its structure. A class variable is shared by all instances of the same class. In C++, a class variable is declared as a static member.

    In summary:

    • Property is a broad concept used to denote a particular characteristic of a class, encompassing both its attributes and its relationships to other classes.

    • Attribute denotes a part of an aggregate object, and so is used during analysis as well as design to express a singular property of the class.

    • Class variable is an attribute defined in a class of which a single copy exists, regardless of how many instances of the class exist. So all instances of that class share its value as well as its declaration.

    • Field is a language-specific term for instance variable, that is, an attribute whose value is specific to each object.

    0 讨论(0)
  • 2020-12-05 05:30

    I discovered in my question that Properties as defined in .Net are just a convenience syntax for code, and they are not tied to underlying variables at all (except for Auto-Implemented Properties, of course). So, saying "what is the difference between class property and class field" is like saying: what is the difference between a method and an attribute. No difference, one is code and the other is data. And, they need not have anything to do with each other.

    It is really too bad that the same words, like "attribute" and "property", are re-used in different languages and ideologies to have starkly different meanings. Maybe someone needs to define an object-oriented language to talk about concepts in OOP? UML?

    0 讨论(0)
提交回复
热议问题