请输入您要查询的百科知识:

 

词条 Encapsulation (computer programming)
释义

  1. General definition

  2. An information-hiding mechanism

  3. Encapsulation and inheritance

  4. References

  5. External links

In object oriented programming languages, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination[1][2] thereof:

  • A language mechanism for restricting direct access to some of the object's components.[3][4]
  • A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.[5][6]

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 is motivated by the fact that in many of the OOP languages hiding of components is not automatic or 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 programming languages, although other alternatives also exist.

General definition

Encapsulation is one of the fundamentals of OOP (object-oriented programming). It refers to the bundling of data with the methods that operate on that data.[5] Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them. Publicly accessible methods are generally provided in the class (so-called getters and setters) to access the values, and other client classes call these methods to retrieve and modify the values within the object.

This mechanism is not unique to object-oriented programming. Implementations of abstract data types, e.g. modules, offer a similar form of encapsulation. This similarity stems from the fact that both notions rely on the same mathematical fundamental of an existential type.[7]

An information-hiding mechanism

{{See also|Information hiding}}{{em| Encapsulation can be used to hide data members and member functions.}} Under this definition, encapsulation means that the internal representation of an object is generally hidden from view outside of the object's definition. Typically, only the object's own methods can directly inspect or manipulate its fields. Some languages like Smalltalk and Ruby only allow access via object methods, but most others (e.g. C++, C#, Delphi or Java) offer the programmer a degree of control over what is hidden, typically via keywords like public and private.[4] 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.

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 inter-dependencies between software components{{Citation needed|date=April 2014}}.

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++.

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 salary;    }
    public static void main() {        Employee e = new Employee();        BigDecimal sal = e.getSalary();    }

}

Below is an example in PHP:

class Account {

    /**     * How much money is currently in the account     * @var float     */    private $accountBalance;
    /**     * @param float $currentAccountBalance Initialize account to this dollar amount     */    public function __construct($currentAccountBalance) {        $this->accountBalance = $currentAccountBalance;    }
    /**     * Add money to account     * @param float $money Dollars to add to balance     * @return void     */    public function deposit($money) {        $this->accountBalance += $money;    }
    /**     * Remove money from account     * @param float $money Dollars to subtract from balance     * @throws Exception     * @return void     */    public function withdraw($money) {        if ($this->accountBalance < $money) {            throw new Exception('Cannot withdraw $' . $money . ' from account as it contains $' . $this->accountBalance);        }        $this->accountBalance -= $money;    }
    /**     * Get current account balance, that takes all additions and subtractions into consideration.     * @return float     */    public function getAccountBalance() {        return $this->accountBalance;    }

}

// Create a new object from the Account class with a starting balance of $500.00

$myAccount = new Account(500.00);

// We have clearly defined methods for adding and subtracting money from the Account

// If we didn't have a method for withdraw(), nothing would prevent us from withdrawing more money than was available in the account

$myAccount->deposit(10.24);

$myAccount->withdraw(4.45);

// Get the current balance

$accountBalance = $myAccount->getAccountBalance();

echo 'My Account Balance: $' . $accountBalance; // 505.79

// Our code forbids us from withdrawing more than we have

$myAccount->withdraw(600.00); // Exception Message: Cannot withdraw $600 from account as it contains $505.79

Encapsulation is also possible in non-object-oriented languages. In C, for example, a structure can be declared in the public API (i.e., 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:

// 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 they won't hurt.

// extern keyword defines functions to have external linkage (i.e. can be called outside current file)

// which is the default behavior even without the keyword extern

Note on extern keyword from K.N. King.[8]

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"

  1. include "api.h"

// Complete definition of the 'Entity' object

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)

{ ... }

Encapsulation and inheritance

The authors of Design Patterns[9] discuss the tension between inheritance and encapsulation at length and state that in their experience, designers overuse inheritance. The danger is stated as follows:

{{quote |text=Because inheritance exposes a subclass to details of its parent's implementation, it's often said that "inheritance breaks encapsulation" |author=Gang of Four |source=Design Patterns[9] (Chapter 1)}}

References

1. ^{{cite book |first=Michael Lee |last=Scott |title=Programming language pragmatics |edition=2 |publisher=Morgan Kaufmann |year=2006 |isbn=978-0-12-633951-2 |page=481 |quote=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.}}
2. ^{{cite book |first=Nell B. |last=Dale |first2=Chip |last2=Weems |title=Programming and problem solving with Java |edition=2nd |publisher=Jones & Bartlett |year=2007 |isbn=978-0-7637-3402-2 |page=396}}
3. ^{{cite book |authorlink=John C. Mitchell |first=John C. |last=Mitchell |title=Concepts in programming languages |publisher=Cambridge University Press |year=2003 |isbn=978-0-521-78098-8 |page=522}}
4. ^{{cite book |last=Pierce |first=Benjamin |authorlink=Benjamin C. Pierce |title=Types and Programming Languages |publisher=MIT Press |year=2002 |isbn=978-0-262-16209-8 |page=266 |ref=harv|title-link=Types and Programming Languages }}
5. ^{{cite web |first=Wm. Paul |last=Rogers |url=http://www.javaworld.com/javaworld/jw-05-2001/jw-0518-encapsulation.html?page=9 |title=Encapsulation is not information hiding |publisher=JavaWorld |date=18 May 2001}}
6. ^{{cite book |first=Thomas M. |last=Connolly |first2=Carolyn E. |last2=Begg |title=Database systems: a practical approach to design, implementation, and management |edition= 4th |publisher=Pearson Education |year=2005 |isbn=978-0-321-21025-8 |chapter=Ch. 25: Introduction to Object DMBS § Object-oriented concepts |page=814}}
7. ^{{harvnb|Pierce|2002|loc=§ 24.2 Data Abstraction with Existentials}}
8. ^King, Kim N. C programming: a modern approach. WW Norton & Company, 2008. Ch. 18, p. 464, {{ISBN|0393979504}}
9. ^{{cite book| last1 = Gamma| first1 = Erich| last2 = Helm| first2 = Richard| last3 = Johnson| first3 = Ralph| last4 = Vlissides| first4 = John| title = Design Patterns| date = 1994| publisher = Addison-Wesley| isbn = 978-0-201-63361-0}}

External links

  • {{Citation/make link|http://wiki.c2.com/?EncapsulationDefinition|Object-Oriented Encapsulation Definition}}
  • {{Citation/make link|http://www.soapatterns.org/service_encapsulation.php|SOA Patterns.org}}
  • {{Citation/make link|http://telecomacadmey.com/understanding-encapsulation-troubleshooting-network/|Encapsulation}}

1 : Object-oriented programming

随便看

 

开放百科全书收录14589846条英语、德语、日语等多语种百科知识,基本涵盖了大多数领域的百科知识,是一部内容自由、开放的电子版国际百科全书。

 

Copyright © 2023 OENC.NET All Rights Reserved
京ICP备2021023879号 更新时间:2024/9/22 14:27:18