What's the difference between an object and a struct in OOP?

后端 未结 10 1766
旧时难觅i
旧时难觅i 2021-01-30 09:05
  • What distinguishes and object from a struct?
  • When and why do we use an object as opposed to a struct?
  • How does an array differ from both, and when and wh
10条回答
  •  日久生厌
    2021-01-30 09:29

    Arrays are ordered collection of items that (usually) are of the same types. Items can be accessed by index. Classic arrays allow integer indices only, however modern languages often provide so called associative arrays (dictionaries, hashes etc.) that allow use e.g. strings as indices.

    Structure is a collection of named values (fields) which may be of 'different types' (e.g. field a stores integer values, field b - string values etc.). They (a) group together logically connected values and (b) simplify code change by hiding details (e.g. changing structure layout don't affect signature of function working with this structure). The latter is called 'encapsulation'.

    Theroretically, object is an instance of structure that demonstrates some behavior in response to messages being sent (i.e., in most languages, having some methods). Thus, the very usefullness of object is in this behavior, not its fields.

    Different objects can demonstrate different behavior in response to the same messages (the same methods being called), which is called 'polymorphism'.

    In many (but not all) languages objects belong to some classes and classes can form hierarchies (which is called 'inheritance').

    Since object methods can work with its fields directly, fields can be hidden from access by any code except for this methods (e.g. by marking them as private). Thus encapsulation level for objects can be higher than for structs.

    Note that different languages add different semantics to this terms.

    E.g.:

    • in CLR languages (C#, VB.NET etc) structs are allocated on stack/in registers and objects are created in heap.

    • in C++ structs have all fields public by default, and objects (instances of classes) have all fields private.

    • in some dynamic languages objects are just associative arrays which store values and methods.

提交回复
热议问题