Share to: share facebook share twitter share wa share telegram print page

Encapsulation (computer programming)

In software systems, encapsulation refers to the bundling of data with the mechanisms or methods that operate on the data. It may also refer to the limiting of direct access to some of that data, such as an object's components.[1] Essentially, encapsulation prevents external code from being concerned with the internal workings of an object.

Encapsulation allows developers to present a consistent interface that is independent of its internal implementation. As one example, encapsulation can be used to hide the values or state of a structured data object inside a class. This prevents clients from directly accessing this information in a way that could expose hidden implementation details or violate state invariance maintained by the methods.

Encapsulation also encourages programmers to put all the code that is concerned with a certain set of data in the same class, which organizes it for easy comprehension by other programmers. Encapsulation is a technique that encourages decoupling.

All object-oriented programming (OOP) systems support encapsulation,[2][3] but encapsulation is not unique to OOP. Implementations of abstract data types, modules, and libraries also offer encapsulation. The similarity has been explained by programming language theorists in terms of existential types.[4]

Meaning

In object-oriented programming languages, and other related fields, encapsulation refers to one of two related but distinct notions, and sometimes to the combination thereof:[5][6]

  • A language mechanism for restricting direct access to some of the object's components.[7][8]
  • A language construct that facilitates the bundling of data with the methods (or other functions) operating on those data.[1][9]

Some programming language researchers and academics use the first meaning alone or in combination with the second as a distinguishing feature of object-oriented programming, while some programming languages that provide lexical closures view encapsulation as a feature of the language orthogonal to object orientation.

The second definition reflects that in many object-oriented languages, and other related fields, the components are not hidden automatically and this can be overridden. Thus, information hiding is defined as a separate notion by those who prefer the second definition.

The features of encapsulation are supported using classes in most object-oriented languages, although other alternatives also exist.

Encapsulation may also refer to containing a repetitive or complex process in a single unit to be invoked. Object-oriented programming facilitate this at both the method and class levels. This definition is also applicable to procedural programming.[10]

Encapsulation and inheritance

The authors of Design Patterns discuss the tension between inheritance and encapsulation at length and state that in their experience, designers overuse inheritance. They claim that inheritance often breaks encapsulation, given that inheritance exposes a subclass to the details of its parent's implementation.[11] As described by the yo-yo problem, overuse of inheritance and therefore encapsulation, can become too complicated and hard to debug.

Information hiding

Under the definition that encapsulation "can be used to hide data members and member functions", the internal representation of an object is generally hidden outside of the object's definition. Typically, only the object's own methods can directly inspect or manipulate its fields. Hiding the internals of the object protects its integrity by preventing users from setting the internal data of the component into an invalid or inconsistent state. A supposed benefit of encapsulation is that it can reduce system complexity, and thus increase robustness, by allowing the developer to limit the interdependencies between software components.[citation needed]

Some languages like Smalltalk and Ruby only allow access via object methods, but most others (e.g., C++, C#, Delphi or Java[12]) offer the programmer some control over what is hidden, typically via keywords like public and private.[8] ISO C++ standard refers to protected, private and public as "access specifiers" and that they do not "hide any information". Information hiding is accomplished by furnishing a compiled version of the source code that is interfaced via a header file.

Almost always, there is a way to override such protection – usually via reflection API (Ruby, Java, C#, etc.), sometimes by mechanism like name mangling (Python), or special keyword usage like friend in C++. Systems that provide object-level capability-based security (adhering to the object-capability model) are an exception, and guarantee strong encapsulation.

Examples

Restricting data fields

Languages like C++, C#, Java,[12] PHP, Swift, and Delphi offer ways to restrict access to data fields.

Below is an example in C# that shows how access to a data field can be restricted through the use of a private keyword:

class Program
{
    public class Account
    {
        private decimal _accountBalance = 500.00m;

        public decimal CheckBalance()
        {
            return _accountBalance;
        }
    }

    static void Main()
    {
        Account myAccount = new Account();
        decimal myBalance = myAccount.CheckBalance();

        /* This Main method can check the balance via the public
         * "CheckBalance" method provided by the "Account" class 
         * but it cannot manipulate the value of "accountBalance" */
    }
}

Below is an example in Java:

public class Employee {
    private BigDecimal salary = new BigDecimal(50000.00);
    
    public BigDecimal getSalary() {
        return this.salary;
    }

    public static void main() {
        Employee e = new Employee();
        BigDecimal sal = e.getSalary();
    }
}

Encapsulation is also possible in non-object-oriented languages. In C, for example, a structure can be declared in the public API via the header file for a set of functions that operate on an item of data containing data members that are not accessible to clients of the API with the extern keyword.[13]

// Header file "api.h"

struct Entity;          // Opaque structure with hidden members

// API functions that operate on 'Entity' objects
extern struct Entity *  open_entity(int id);
extern int              process_entity(struct Entity *info);
extern void             close_entity(struct Entity *info);
// extern keywords here are redundant, but don't hurt.
// extern defines functions that can be called outside the current file, the default behavior even without the keyword

Clients call the API functions to allocate, operate on, and deallocate objects of an opaque data type. The contents of this type are known and accessible only to the implementation of the API functions; clients cannot directly access its contents. The source code for these functions defines the actual contents of the structure:

// Implementation file "api.c"

#include "api.h"

struct Entity {
    int     ent_id;         // ID number
    char    ent_name[20];   // Name
    ... and other members ...
};

// API function implementations
struct Entity * open_entity(int id)
{ ... }

int process_entity(struct Entity *info)
{ ... }

void close_entity(struct Entity *info)
{ ... }

Name mangling

Below is an example of Python, which does not support variable access restrictions. However, the convention is that a variable whose name is prefixed by an underscore should be considered private.[14]

class Car: 
    def __init__(self) -> None:
        self._maxspeed = 200
 
    def drive(self) -> None:
        print(f"Maximum speed is {self._maxspeed}.")
 
redcar = Car()
redcar.drive()  # This will print 'Maximum speed is 200.'

redcar._maxspeed = 10
redcar.drive()  # This will print 'Maximum speed is 10.'

See also

Citations

  1. ^ a b Rogers, Wm. Paul (18 May 2001). "Encapsulation is not information hiding". JavaWorld. Retrieved 2020-07-20.
  2. ^ "What is Object-Oriented Programming (OOP)?". App Architecture. Retrieved 2024-03-02.
  3. ^ "Encapsulation in Object Oriented Programming (OOPS)". www.enjoyalgorithms.com. Retrieved 2024-03-02.
  4. ^ Pierce 2002, § 24.2 Data Abstraction with Existentials
  5. ^ Scott, Michael Lee (2006). Programming language pragmatics (2 ed.). Morgan Kaufmann. p. 481. ISBN 978-0-12-633951-2. Encapsulation mechanisms enable the programmer to group data and the subroutines that operate on them together in one place, and to hide irrelevant details from the users of an abstraction
  6. ^ Dale, Nell B.; Weems, Chip (2007). Programming and problem solving with Java (2nd ed.). Jones & Bartlett. p. 396. ISBN 978-0-7637-3402-2.
  7. ^ Mitchell, John C. (2003). Concepts in programming languages. Cambridge University Press. p. 522. ISBN 978-0-521-78098-8.
  8. ^ a b Pierce, Benjamin (2002). Types and Programming Languages. MIT Press. p. 266. ISBN 978-0-262-16209-8.
  9. ^ Connolly, Thomas M.; Begg, Carolyn E. (2005). "Ch. 25: Introduction to Object DMBS § Object-oriented concepts". Database systems: a practical approach to design, implementation, and management (4th ed.). Pearson Education. p. 814. ISBN 978-0-321-21025-8.
  10. ^ McDonough, James E. (2017). "Encapsulation". Object-Oriented Design with ABAP: A Practical Approach. Apress. doi:10.1007/978-1-4842-2838-8. ISBN 978-1-4842-2837-1 – via O'Reilly.{{cite book}}: CS1 maint: date and year (link)
  11. ^ Gamma, Erich; Helm, Richard; Johnson, Ralph; Vlissides, John (1994). Design Patterns. Addison-Wesley. ISBN 978-0-201-63361-0.
  12. ^ a b Bloch 2018, pp. 73–77, Chapter §4 Item 15 Minimize the accessibility of classes and members.
  13. ^ King, K. N. (2008). C Programming: A Modern Approach (2nd ed.). W. W. Norton & Company. p. 464. ISBN 978-0393979503.
  14. ^ Bader, Dan. "The Meaning of Underscores in Python". Improve Your Python Skills. Retrieved 1 November 2019.

References

  • Bloch, Joshua (2018). "Effective Java: Programming Language Guide" (third ed.). Addison-Wesley. ISBN 978-0134685991.

Read other articles:

Overview of the role of Buddhism in Thailand Buddhism in ThailandWat Phra Kaew, one of the most sacred wats in BangkokTotal populationc. 64 million (95%) in 2015[1][2]Regions with significant populationsThroughout ThailandReligions Theravada BuddhismLanguagesThai and other languages Part of a series onTheravāda Buddhism Countries Bangladesh Cambodia China India Laos Myanmar Nepal Sri Lanka Thailand Vietnam Western world Texts Pāli Tipiṭaka Paracanonical texts Comment...

 

Penyewaan sepeda seperti Capital Bikeshare di Washington, D.C. telah disebut sebagai salah satu cara mengatasi masalah mil terakhir. Mil terakhir (bahasa Inggris: last mile) adalah istilah yang digunakan dalam manajemen rantai suplai dan perencanaan transportasi untuk menggambarkan pergerakan orang dan barang dari pusat transportasi ke tujuan akhir di rumah.[1] Penggunaan dalam jaringan distribusi Istilah mil terakhir pada awalnya digunakan di bidang telekomunikasi tetapi sejak it...

 

ثنائي أمين الإيثيلين رباعي حمض الأسيتيك ثنائي أمين الإيثيلين رباعي حمض الأسيتيك ثنائي أمين الإيثيلين رباعي حمض الأسيتيك الاسم النظامي (IUPAC) 2,2',2'',2'''-(ethane-1,2-diyldinitrilo)tetraacetic acid أسماء أخرى EDTA, H4EDTA,Diaminoethane-tetraacetic acid,Edetic acid, Edetate, Ethylenedinitrilo-tetraacetic acid,Versene, ثنائي أمين الإيثلين - رباعي حم...

Charlotte von Stein Charlotte von Stein (Eisenach, 25 december 1742 - Weimar, 6 januari 1827), geboren Albertine Ernestine Charlotte von Schardt, was een Duitse adellijke vrouw, hofdame en schrijfster. Zij was jarenlang de hartsvriendin van Johann Wolfgang von Goethe, en was ook goed bevriend met Friedrich Schiller en Johann Gottfried von Herder. Zij correspondeerde uitvoerig met Goethe en schreef op latere leeftijd een aantal toneelwerken, waarin ze op ironisch-wrange wijze terugkijkt op hun...

 

هذه مقالة غير مراجعة. ينبغي أن يزال هذا القالب بعد أن يراجعها محرر مغاير للذي أنشأها؛ إذا لزم الأمر فيجب أن توسم المقالة بقوالب الصيانة المناسبة. يمكن أيضاً تقديم طلب لمراجعة المقالة في الصفحة المخصصة لذلك. (سبتمبر 2023) الأدب[1] الفرنسي في القرن التاسع عشر يتعلق الأدب الف�...

 

American college football rivalry Army–Notre Dame football rivalry Army Black Knights Notre Dame Fighting Irish First meetingNovember 1, 1913Notre Dame, 35–13Latest meetingNovember 12, 2016Notre Dame, 44–6StatisticsMeetings total51All-time seriesNotre Dame leads, 39–8–4[1]Largest victoryArmy, 59–0 (1944)Notre Dame, 62–3 (1973)Longest win streakNotre Dame, 15 (1965–present)Current win streakNotre Dame, 15 (1965–present) [Interactive fullscreen map + nearby articles] L...

Part of a building Ground floor redirects here. For the bottom floor of a building which lacks a basement, see solid ground floor. For the sitcom, see Ground Floor. For other uses, see Storey (disambiguation). This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. U...

 

لا يزال النص الموجود في هذه الصفحة في مرحلة الترجمة إلى العربية. إذا كنت تعرف اللغة المستعملة، لا تتردد في الترجمة. تتضمن هذه المقالة محارف خاصة. من غير تصيير مناسب، قد تظهر علامات استفهام أو صناديقَ أو رموزٌ أخرى. في المنطق، تُستخدم مجموعة من الرموز للتعبير عن مفاهيمَ منطق�...

 

Species of annelid worm Red earthworm Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Annelida Class: Clitellata Order: Opisthopora Family: Lumbricidae Genus: Lumbricus Species: L. rubellus Binomial name Lumbricus rubellusHoffmeister, 1843 Lumbricus rubellus is a species of earthworm that is related to Lumbricus terrestris. It is usually reddish brown or reddish violet, iridescent dorsally, and pale yellow ventrally. They are usually about 25 millimetres (0.98 ...

West Bengal Legislative Assembly constituency BallygungeConstituency No. 161 for the West Bengal Legislative AssemblyInteractive Map Outlining Ballygunge Assembly ConstituencyConstituency detailsCountryIndiaRegionEast IndiaStateWest BengalDistrictKolkataLS constituencyKolkata DakshinEstablished1952Total electors247,623ReservationNoneMember of Legislative Assembly17th West Bengal Legislative AssemblyIncumbent Babul Supriyo PartyAll India Trinamool CongressElected year2022 Ballygunge Assembly c...

 

American basketball player and coach This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: Cliff Hagan – news · newspapers · books · scholar · JSTOR (June 2021) (Learn how and when to remove this temp...

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (يوليو 2019) هانا روس معلومات شخصية الميلاد 28 يناير 1990 (33 سنة)  بوكاتيلو  الجنسية الولايات المتحدة  الحياة العملية الفرق رالي سايكلنج  [لغات أخرى]‏ (2016–) ...

Halaman ini berisi artikel tentang film Italia 1990. Untuk film Inggris 2005, lihat The Open Doors. Porte aperteSutradara Gianni Amelio ProduserDitulis oleh Gianni Amelio Vincenzo Cerami Alessandro Sermoneta PemeranGian Maria VolontéEnnio FantastichiniRenato CarpentieriPenata musikFranco PiersantiSinematograferTonino NardiPenyuntingSimona PaggiDistributorOrion Pictures di AS, 1991Tanggal rilis 29 Maret 1990 (1990-03-29) Durasi108 menitNegara Italia Bahasa Italia Open Doors (bahasa...

 

167-ма піхотна дивізія (Третій Рейх)167. Infanterie-Division Емблема 167-ї піхотної дивізії ВермахтуНа службі 26 листопада 1939 — лютий 1944Країна  Третій РейхНалежність  ВермахтВид  Сухопутні військаРоль піхотаЧисельність піхотна дивізіяУ складі VII-й військовий округРезерв...

 

Music and musical traditions of Kazakhstan This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Music of Kazakhstan – news · newspapers · books · scholar · JSTOR (October 2018) (Learn how and when to remove this template message) Music of Central Asia Kazakhstan Kyrgyzstan Mongolia Tajikistan Turkmenistan Uzbekis...

Media ownership in Australia redirects here. For a listing of media companies in Australia, see Category:Mass media companies of Australia. Overview of mass media in Australia Adults employed in the information media and telecommunications industries as a percentage of the adult population in Australia divided geographically by statistical local area, as of the 2011 census Mass media in Australia spans traditional and digital formats, and caters mostly to its predominantly English-speaking po...

 

1973 studio album by Etta JamesEtta JamesStudio album by Etta JamesReleased1973RecordedSunset Sound Factory, Hollywood, CaliforniaGenreFunk, Soul, R&BLabelChessCH-50042ProducerGabriel MeklerEtta James chronology Losers Weepers(1971) Etta James(1973) Come a Little Closer(1974) Professional ratingsReview scoresSourceRatingAllMusic[1]Christgau's Record GuideB[2] Etta James (also known as Only a Fool) is the tenth studio album by American blues artist Etta James, relea...

 

This article is about the Burl Ives album. For the song, see A Holly Jolly Christmas. 1965 studio album by Burl IvesHave a Holly Jolly ChristmasStudio album by Burl IvesReleasedOctober 1965RecordedBrooklyn StudiosGenreChristmas, folk, popLength29:28LabelDeccaProducerMilt GablerBurl Ives chronology On the Beach at Waikiki(1965) Have a Holly Jolly Christmas(1965) Shall We Gather at the River?(1965) Professional ratingsReview scoresSourceRatingAllmusic [1] Have a Holly Jolly Chri...

Disambiguazione – Se stai cercando altri significati, vedi High School Musical (disambigua). High School MusicalTitolo originaleHigh School Musical PaeseStati Uniti d'America Anno2006 Formatofilm TV Generemusicale, commedia, adolescenziale Durata97 min Lingua originaleinglese, spagnolo Rapporto16:9 CreditiRegiaKenny Ortega SceneggiaturaPeter Barsocchini Interpreti e personaggi Zac Efron: Troy Bolton Vanessa Hudgens: Gabriella Montez Ashley Tisdale: Sharpay Evans Corbin Bleu: Chad Da...

 

Bozsik Medallista olímpico Datos personalesNombre completo József BozsikApodo(s) CucuNacimiento Kispest (Budapest), Hungría28 de noviembre de 1925Nacionalidad(es) Húngaro HúngaroFallecimiento Budapest (Hungría)31 de mayo de 1978 (52 años)Carrera deportivaDeporte FútbolClub profesionalDebut deportivo 1938 (como jugador)1966 (como entrenador)(Budapest Honvéd F. C. (como jugador)Budapest Honvéd F. C. (como entrenador))Posición MediocampistaRetirada deportiva 1962 (como jugad...

 
Kembali kehalaman sebelumnya