Object composition

In computer science, object composition and object aggregation are closely related ways to combine objects or data types into more complex ones. In conversation, the distinction between composition and aggregation is often ignored.[1] Common kinds of compositions are objects used in object-oriented programming, tagged unions, sets, sequences, and various graph structures. Object compositions relate to, but are not the same as, data structures.

Object composition refers to the logical or conceptual structure of the information, not the implementation or physical data structure used to represent it[citation needed]. For example, a sequence differs from a set because (among other things) the order of the composed items matters for the former but not the latter. Data structures such as arrays, linked lists, hash tables, and many others can be used to implement either of them. Perhaps confusingly, some of the same terms are used for both data structures and composites. For example, "binary tree" can refer to either: as a data structure it is a means of accessing a linear sequence of items, and the actual positions of items in the tree are irrelevant (the tree can be internally rearranged however one likes, without changing its meaning). However, as an object composition, the positions are relevant, and changing them would change the meaning (as for example in cladograms)[citation needed].

Programming technique

Object-oriented programming is based on using objects to encapsulate data and behavior. It uses two main techniques for assembling and composing functionality into more complex ones, sub-typing and object composition.[2] Object composition is about combining objects within compound objects, and at the same time, ensuring the encapsulation of each object by using their well-defined interface without visibility of their internals. In this regard, object composition differs from data structures, which do not enforce encapsulation.

Object composition may also be about a group of multiple related objects, such as a set or a sequence of objects. Delegation may enrich composition by forwarding requests or calls made to the enclosing composite object to one of its internal components.[3]

In class-based and typed programming languages, types can be divided into composite and non-composite types, and composition can be regarded as a relationship between types: an object of a composite type (e.g. car) "has" objects of other types (e.g. wheel). When a composite object contains several sub-objects of the same type, they may be assigned to particular roles, often distinguished by names or numbers. For example, a Point object might contain 3 numbers, each representing distance along a different axis, such as 'x', 'y', and 'z'. The study of part-whole relationships in general, is mereology.

Composition must be distinguished from subtyping, which is the process of adding detail to a general data type to create a more specific data type. For instance, cars may be a specific type of vehicle: car is a vehicle. Subtyping doesn't describe a relationship between different objects, but instead, says that objects of a type are simultaneously objects of another type. The study of such relationships is ontology.

In prototype-based programming languages such as JavaScript, objects can dynamically inherit the behaviors from a prototype object at the moment of their instantiation. Composition must be distinguished from prototyping: the newly instantiated object inherits the composition of its prototype, but it may itself be composed on its own.

Composite objects may be represented in storage by co-locating the composed objects, by co-locating references, or in many other ways. The items within a composite object may be referred to as attributes, fields, members, properties, or other names, and the resulting composition as composite type, storage record, structure, tuple, or a user-defined type (UDT). For details, see the aggregation section below.

UML modeling technique

A bycicle class represented in UML, with three properties: saddle, wheels and parts, the two last having a multiplicity indicating several objects
Object composition using UML properties to compose objects

In UML modeling, objects can be conceptually composed, independently of the implementation with a programming language. There are four ways of composing objects in UML: property, association, aggregation and composition:[4]

  • A property represents an attribute of the class.
  • An association represents a semantic relationship between instances of the associated classes. The member-end of an association corresponds to a property of the associated class.
  • An aggregation is a kind of association that models a part/whole relationship between an aggregate (whole) and a group of related components (parts).
  • A composition, also called a composite aggregation, is a kind of aggregation that models a part/whole relationship between a composite (whole) and a group of exclusively owned parts.

The relationship between the aggregate and its components is a weak "has-a" relationship: The components may be part of several aggregates, may be accessed through other objects without going through the aggregate, and may outlive the aggregate object.[4] The state of the component object still forms part of the aggregate object.[citation needed]

The relationship between the composite and its parts is a strong “has-a” relationship: The composite object has sole "responsibility for the existence and storage of the composed objects", the composed object can be part of at most one composite, and "If a composite object is deleted, all of its part instances that are objects are deleted with it". Thus in UML, composition has a more narrow meaning than the usual object composition.

Association between several bicycles each having one owner; Composition of a bicycle with frame parts which make the bicycle; and aggregation of a bicycle with its wheels, which exist without the bicycle
UML notation for association, composition and aggregation

The graphical notation represents:

  • the property as a typed element in the box of the enclosing class,
  • the association as a plain line between the associated classes,
  • the aggregation as an unfilled diamond on the side of the aggregate and a solid line,
  • the composition as a filled diamond on the side of the composite and a solid line.

Aggregation

Aggregation differs from ordinary composition in that it does not imply ownership. In composition, when the owning object is destroyed, so are the contained objects. In aggregation, this is not necessarily true. For example, a university owns various departments (e.g., chemistry), and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a university can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a professor could work in more than one department, but a department could not be part of more than one university.

Composition is usually implemented such that an object contains another object. For example, in C++:

class Professor;  // Defined elsewhere

class Department {
 public:
  Department(const std::string& title): title_(title) {}

 private:
  // Aggregation: |Professors| may outlive the |Department|.
  std::vector<std::weak_ptr<Professor>> members_;
  const std::string title_;
};


class University {
 public:
  University() = default;

 private:
  // Composition: |Department|s exist only as long as the faculty exists.
  std::vector<Department> faculty_ = {
      Department("chemistry"),
      Department("physics"),
      Department("arts"),
  };
};

In aggregation, the object may only contain a reference or pointer to the object (and not have lifetime responsibility for it).

Sometimes aggregation is referred to as composition when the distinction between ordinary composition and aggregation is unimportant.

The above code would transform into the following UML Class diagram:

Aggregation in COM

Aggregation in COM

In Microsoft's Component Object Model, aggregation means that an object exports, as if it were their owner, one or several interfaces of another object it owns. Formally, this is more similar to composition or encapsulation than aggregation. However, instead of implementing the exported interfaces by calling the interfaces of the owned object, the interfaces of the owned object themselves are exported. The owned object is responsible for assuring that methods of those interfaces inherited from IUnknown actually invoke the corresponding methods of the owner. This is to guarantee that the reference count of the owner is correct and all interfaces of the owner are accessible through the exported interface, while no other (private) interfaces of the owned object are accessible.[5]

Special forms

Containment

Composition that is used to store several instances of the composited data type is referred to as containment. Examples of such containers are arrays, associative arrays, binary trees, and linked lists.

In UML, containment is depicted with a multiplicity of 0..* or 1..*, indicating that the composite object is composed of an unknown number of instances of the composed class.

Recursive composition

Objects can be composed recursively, and their type is then called recursive type. Examples includes various kinds of trees, DAGs, and graphs. Each node in a tree may be a branch or leaf; in other words, each node is a tree at the same time when it belongs to another tree.

In UML, recursive composition is depicted with an association, aggregation or composition of a class with itself.

Composite pattern

The composite design pattern is an object-oriented design based on composite types, that combines recursive composition and containment to implement complex part-whole hierarchies.

Composite types in C

This is an example of composition in C.

struct Person
{
  int age;
  char name[20];
  enum {job_seeking, professional, non_professional, retired, student} employment;
};

In this example, the primitive (noncomposite) types int, enum {job_seeking, professional, non_professional, retired, student} and the composite array type char[] are combined to form the composite structure Person. Each Person structure then "has an" age, name, and an employment type.

Timeline of composition in various languages

C calls a record a struct or structure; object-oriented languages such as Java, Smalltalk, and C++ often keep their records hidden inside objects (class instances); languages in the ML family simply call them records. COBOL was the first widespread programming language to support records directly;[6] ALGOL 68 got it from COBOL and Pascal got it, more or less indirectly, from ALGOL 68. Common Lisp provides structures and classes (the latter via the Common Lisp Object System).[citation needed]

1959 – COBOL
      01  customer-record.
        03  customer-number     pic 9(8) comp.
        03  customer-name.
          05  given-names       pic x(15).
          05  initial-2         pic x.
          05  surname           pic x(15).
        03  customer-address.
          05  street.
            07  street-name     pic x(15).
              09  house-number  pic 999 comp.
          05  city              pic x(10).
          05  country-code      pic x(3).
          05  postcode          pic x(8).
        03  amount-owing        pic 9(8) comp.
1960 – ALGOL 60

Arrays were the only composite data type in Algol 60.

1964 – PL/I
dcl 1 newtypet based (P);
 2 (a, b, c) fixed bin(31),
 2 (i, j, k) float,
 2 r ptr;
allocate newtypet;
1968 – ALGOL 68
int max = 99;
mode newtypet = [0..9] [0..max]struct (
 long real a, b, c, short int i, j, k, ref real r
);
newtypet newarrayt = (1, 2, 3, 4, 5, 6, heap real := 7)

For example, a linked list might be declared as:

mode node = union (real, int, compl, string),
 list = struct (node val, ref list next);

For ALGOL 68 only the type name appears to the left of the equality, and most notably the construction is made – and can be read – from left to right without regard to priorities.

1970 – Pascal
type
 a = array [1..10] of integer;
 b = record
  a, b, c: real;
  i, j, k: integer;
 end;
1972 – K&R C
#define max 99
struct newtypet {
  double a, b, c;
  float r;
  short i, j, k;
} newarrayt[10] [max + 1];
1977 – FORTRAN 77

Fortran 77 has arrays, but lacked any formal record/structure definitions. Typically compound structures were built up using EQUIVALENCE or COMMON statements:

       CHARACTER NAME*32, ADDR*32, PHONE*16
       REAL OWING
       COMMON /CUST/NAME, ADDR, PHONE, OWING
1983 – Ada
type Cust is
 record
  Name  : Name_Type;
  Addr  : Addr_Type;
  Phone : Phone_Type;
  Owing : Integer range 1..999999;
 end record;

Ada 95 brought OOP concepts through tagged types (the equivalent of a C++ class), Ada 2012 added support for substitution verification through class-wide contracts.

1983 – C++
const int max = 99;
class {
  public:
  double a, b, c;
  float &r;
  short i, j, k;
}newtypet[10] [max + 1];
1991 – Python
max = 99
class NewTypeT:
    def __init__(self):
        self.a = self.b = self.c = 0
        self.i = self.j = self.k = 0.0
# Initialise an example array of this class.
newarrayt = [[NewTypeT() for i in range(max + 1)] for j in range(10)]
1992 – FORTRAN 90

Arrays and strings were inherited from FORTRAN 77, and a new reserved word was introduced: type

type newtypet
 double precision a, b, c
 integer*2 i, j, k
* No pointer type REF REAL R
 end type

type (newtypet) t(10, 100)

FORTRAN 90 updated and included FORTRAN IV's concept called NAMELIST.

INTEGER :: jan = 1, feb = 2, mar = 3, apr = 4
NAMELIST / week / jan, feb, mar, apr
1994 – ANSI Common Lisp

Common Lisp provides structures and the ANSI Common Lisp standard added CLOS classes.

(defclass some-class ()
  ((f :type float)
   (i :type integer)
   (a :type (array integer (10)))))

For more details about composition in C/C++, see Composite type.

See also

References

  1. ^ Yaiser, Michelle. "Object-oriented programming concepts: Composition and aggregation". Archived from the original on April 8, 2015. There is a closely related concept to composition called aggregation. In conversation the differences between composition and aggregation are often ignored.
  2. ^ Design patterns : elements of reusable object-oriented software. Gamma, Erich., Helm, Richard (Computer scientist), Johnson, Ralph E., 1955-, Vlissides, John. Reading, Mass.: Addison-Wesley. 1995. ISBN 0-201-63361-2. OCLC 31171684.{{cite book}}: CS1 maint: others (link)
  3. ^ Ostermann, Klaus; Mezini, Mira (October 1, 2001). "Object-oriented composition untangled". ACM SIGPLAN Notices. 36 (11): 283–299. doi:10.1145/504311.504303. ISSN 0362-1340.
  4. ^ a b OMG (2017). "Unified Modeling Language Specification Version 2.5.1". www.omg.org. p. 109-110,197-201. Retrieved October 4, 2020.
  5. ^ "Aggregation". Platform SDK for Windows XP SP2. Microsoft. Retrieved November 4, 2007.
  6. ^ Sebesta, Robert W. Concepts of Programming Languages (Third ed.). Addison-Wesley Publishing Company, Inc. p. 218. ISBN 0-8053-7133-8.

Read other articles:

KaryamuktiDesa Pemandangan Desa KaryamuktiNegara IndonesiaProvinsiJawa BaratKabupatenMajalengkaKecamatanPanyingkiranKode pos45459Kode Kemendagri32.10.18.2009 Luas3.05 km²Jumlah penduduk5592 jiwaKepadatan1520,84 jiwa/km²Jumlah RT29 RTJumlah RW6 RWSitus webkaryamukti.com Karyamukti adalah desa di kecamatan Panyingkiran, Majalengka, Jawa Barat, Indonesia. Desa ini terbagi menjadi 2 Dusun yang dibatasi oleh Jl. Raya Siliwangi Km. 7. Desa Karyamukti merupakan Desa yang mempunyai arti tersen...

 

Часть серии статей о Холокосте Идеология и политика Расовая гигиена · Расовый антисемитизм · Нацистская расовая политика · Нюрнбергские расовые законы Шоа Лагеря смерти Белжец · Дахау · Майданек · Малый Тростенец · Маутхаузен ·&...

 

Sungai LekopancingEtimologiLekopancing dalam Bahasa Makassar, terdiri dari dua kata yaitu Leko artinya daun sirih dan Pancing artinya bersih. Jadi, Lekopancing berarti daun sirih yang bersih.LokasiNegara IndonesiaProvinsiSulawesi SelatanKabupatenMarosInformasi lokalZona waktuWITA (UTC+8) Sungai Lekopancing (Bahasa Inggris: Lekopancing River) adalah sebuah sungai yang terletak di wilayah Kabupaten Maros, Provinsi Sulawesi Selatan, Indonesia. Sungai Lekopancing telah dijadikan sebagai sumb...

Ne Winနေဝင်းNe Win pada tahun 1959 Ketua Partai Program Sosialis BurmaMasa jabatan4 Juli 1962 – 23 Juli 1988 PendahuluPartai didirikanPenggantiSein LwinPresiden Myanmar ke-4Masa jabatan2 Maret 1962 – 9 November 1981(Ketua Persatuan Dewan Revolusioner sampai 2 Maret 1974) PendahuluWin Maung (1962)PenggantiSan YuPerdana Menteri Myanmar ke-3Masa jabatan29 Oktober 1958 – 4 April 1960 PendahuluU NuPenggantiU NuMasa jabatan2 Maret 1962 – 2 Mar...

 

كأس بلغاريا 2015–16 تفاصيل الموسم كأس بلغاريا  النسخة 94  البلد بلغاريا  التاريخ بداية:23 سبتمبر 2015  نهاية:24 مايو 2016  المنظم اتحاد بلغاريا لكرة القدم  البطل سسكا صوفيا  مباريات ملعوبة 33   عدد المشاركين 32   كأس بلغاريا 2014–15  كأس بلغاريا 2016–17  تعديل مصد...

 

† Человек прямоходящий Научная классификация Домен:ЭукариотыЦарство:ЖивотныеПодцарство:ЭуметазоиБез ранга:Двусторонне-симметричныеБез ранга:ВторичноротыеТип:ХордовыеПодтип:ПозвоночныеИнфратип:ЧелюстноротыеНадкласс:ЧетвероногиеКлада:АмниотыКлада:Синапсиды�...

Artikel ini memiliki beberapa masalah. Tolong bantu memperbaikinya atau diskusikan masalah-masalah ini di halaman pembicaraannya. (Pelajari bagaimana dan kapan saat yang tepat untuk menghapus templat pesan ini) Artikel ini tidak memiliki referensi atau sumber tepercaya sehingga isinya tidak bisa dipastikan. Tolong bantu perbaiki artikel ini dengan menambahkan referensi yang layak. Tulisan tanpa sumber dapat dipertanyakan dan dihapus sewaktu-waktu.Cari sumber: Mitsubishi F-2 – ...

 

Questa voce o sezione sull'argomento baseball non cita le fonti necessarie o quelle presenti sono insufficienti. Puoi migliorare questa voce aggiungendo citazioni da fonti attendibili secondo le linee guida sull'uso delle fonti. Stati Uniti Sport Baseball Federazione USA Baseball Confederazione COPABE World Baseball Classic Partecipazioni 4 (esordio: 2006) Miglior risultato 1º Giochi olimpici Partecipazioni 5 (esordio: 1992) Miglior risultato 1° Mondiali Partecipazioni 23 (esordio: 19...

 

Largest known fish species See also: List of longest fish Life restoration of the extinct Leedsichthys, one of the largest bony fish to have ever lived Fish vary greatly in size. The whale shark and basking shark exceed all other fish by a considerable margin in weight and length. Fish are a paraphyletic group that describes aquatic vertebrates while excluding tetrapods, and the bony fish that often represent the group are more closely related to cetaceans such as whales, than to the cartilag...

No debe confundirse con Nutria marina.   Nutria gigante Estado de conservaciónEn peligro (UICN 3.1)[1]​TaxonomíaReino: AnimaliaFilo: ChordataSubfilo: VertebrataClase: MammaliaOrden: CarnivoraSuborden: CaniformiaFamilia: MustelidaeSubfamilia: LutrinaeDistribución Distribución de P. brasiliensis[editar datos en Wikidata] La nutria gigante, lobo gargantilla, arirai o ariray (Pteronura brasiliensis) es una especie de mamífero carnívoro que pertenece a la subfamilia...

 

Rapid transit system in Santiago, Chile Santiago MetroNS 93 train on an elevated portion of the line 5.AS-2014 train on the line 6 side of Los Leones.OverviewNative nameMetro de SantiagoLocaleSantiago, ChileTransit typeRapid transitNumber of lines7[1]Number of stations143[1]Daily ridership2.35 million (avg. weekday, 2017)[2]Annual ridership685 million (2017)[2]WebsiteMetro de SantiagoOperationBegan operation15 September 1975[3]Operator(s)es:Metro S.A.Te...

 

 本表是動態列表,或許永遠不會完結。歡迎您參考可靠來源來查漏補缺。 潛伏於中華民國國軍中的中共間諜列表收錄根據公開資料來源,曾潛伏於中華民國國軍、被中國共產黨聲稱或承認,或者遭中華民國政府調查審判,為中華人民共和國和中國人民解放軍進行間諜行為的人物。以下列表以現今可查知時間為準,正確的間諜活動或洩漏機密時間可能早於或晚於以下所歸�...

المشير عبد ربه منصور هادي الرئيس الثاني للجمهورية اليمنية في المنصب25 فبراير 2012 – 7 أبريل 2022 رئيس الوزراء علي محمد مجور محمد سالم باسندوة خالد محفوظ بحاح أحمد عبيد بن دغر معين عبد الملك سعيد نائب الرئيس خالد محفوظ بحاح علي محسن الأحمر علي عبد الله صالح رشاد محمد العليم...

 

English Victoria Cross recipient (1893–1982) Cyril Edward GourleyBorn19 January 1893Liverpool, EnglandDied31 January 1982 (aged 89)Haslemere, Surrey, EnglandBuriedGrange Cemetery, West Kirby, Wirral, EnglandAllegiance United KingdomService/branch British ArmyYears of service1914–1919RankCaptainUnitRoyal Field ArtilleryBattles/warsWorld War IAwardsVictoria CrossMilitary MedalCroix de guerre (France)[1] Captain Cyril Edward Gourley VC MM (19 January 1893 – 31 Januar...

 

For related races, see 1964 United States gubernatorial elections. 1964 Washington gubernatorial election ← 1960 November 3, 1964 1968 →   Nominee Daniel J. Evans Albert Rosellini Party Republican Democratic Popular vote 697,256 548,692 Percentage 55.8% 43.9% County resultsEvans:      50–60%      60–70%      70–80%Rosellini:      50–60% Governor before e...

Commune and city in Atlantique Department, BeninAlladaCommune and cityAlladaLocation in BeninCoordinates: 6°39′N 2°09′E / 6.650°N 2.150°E / 6.650; 2.150Country BeninDepartmentAtlantique DepartmentArea • Total381 km2 (147 sq mi)Population (2013) • Total127,512Websitehttp://www.web-africa.org/allada/ Allada is a town, arrondissement, and commune, located in the Atlantique Department of Benin. The current town of Al...

 

Scottish actor and comedian (born 1942) For the Netflix character Billie Connelly, see Sex/Life. SirBilly ConnollyCBEConnolly at the premiere of Brave in 2012Birth nameWilliam ConnollyBorn (1942-11-24) 24 November 1942 (age 81)Anderston, Glasgow, ScotlandMediumFilmstand-uptelevisionYears active1965–presentGenresScottish comedyblue comedymusical comedyobservational comedySpouse Iris Pressagh ​ ​(m. 1969; div. 1985)​ Pamela Stephenson&...

 

Nándor Hidegkuti Nándor Hidegkuti en 1965. Biographie Nationalité Hongrois Naissance 3 mars 1922 Budapest (Hongrie) Décès 14 février 2002 (à 79 ans) Budapest (Hongrie) Taille 1,76 m (5′ 9″) Période pro. 1940 – 1958 Poste Attaquant puis entraîneur Parcours professionnel1 AnnéesClub 0M.0(B.) 1940-1943 Gázmüvek 1943-1945 Elektromos 053 0(27) 1945-1947 Herminamezei AC 1947-1958 MTK 314 (226) Sélections en équipe nationale2 AnnéesÉquipe 0M.0(B.) 1945-1958 Hong...

American teen drama television series The Secret Life of the American TeenagerAlso known asSecret LifeGenreTeen dramaCreated byBrenda HamptonStarring Shailene Woodley Kenny Baumann Mark Derwin India Eisley Greg Finley Daren Kagasoff Jorge-Luis Pallo Megan Park Francia Raisa Molly Ringwald Steve Schirripa Theme music composerDan FoliartOpening themeLet's Do It, Let's Fall In Love, performed by Molly RingwaldComposerDan FoliartCountry of originUnited StatesOriginal languageEnglishNo. of seasons...

 

此條目需要編修,以確保文法、用詞、语气、格式、標點等使用恰当。 (2017年1月4日)請按照校對指引,幫助编辑這個條目。(幫助、討論) 巴赫里马木留克的最大疆界,蓝色表示伊尔汗国。 巴赫里王朝,又名拜赫里耶的马木留克(al-Mamalik al-Bahariyya المماليك البحرية),由钦察突厥人建立的马木留克政权,自1250年至1382年统治埃及,后被另一个马木留克政权布尔吉王朝...