Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Encapsulation (computer programming)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==== Restricting data fields ==== Languages like [[C++]], [[C Sharp (programming language)|C#]], [[Java (programming language)|Java]],{{sfn|Bloch|2018|loc=Chapter §4 Item 15 Minimize the accessibility of classes and members|pp=73-77}} [[PHP]], [[Swift (programming language)|Swift]], and [[Delphi (programming language)|Delphi]] offer ways to restrict access to data fields. [[File:UML encapsulation.svg]] Below is an example in [[C Sharp (programming language)|C#]] that shows how access to a data field can be restricted through the use of a <code>private</code> keyword: <syntaxhighlight lang="csharp"> 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" */ } } </syntaxhighlight> Below is an example in [[Java (programming language)|Java]]: <syntaxhighlight lang="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(); } } </syntaxhighlight> <!--Below is an example in [[PHP]]: <syntaxhighlight lang="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): null { $this->accountBalance += $money; } /** * Remove money from account * @param float $money Dollars to subtract from balance * @throws Exception * @return void */ public function withdraw($money): null { 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 </syntaxhighlight> Below is an example in [[Swift (programming language)|Swift]]. The <code>balance</code> property cannot be accessed directly; a merchant can only check whether the requested amount is available for spending using the <code>isAvailable(_:)</code> method. <syntaxhighlight lang="swift"> struct CreditCard { private var balance: Double init(withBalance balance: Double) { self.balance = balance } func isAvailable(_ amount: Double) -> Bool { return balance >= amount } } var myCard = CreditCard(withBalance: 100) myCard.balance // Error: 'balance' is inaccessible due to 'private' protection level myCard.isAvailable(100) // true myCard.isAvailable(101) // false </syntaxhighlight>--> Encapsulation is also possible in non-object-oriented languages. In [[C (programming language)|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 <code>extern</code> keyword.<ref>{{cite book |last1=King |first1=K. N. |url= |title=C Programming: A Modern Approach |date=2008 |publisher=W. W. Norton & Company |isbn=978-0393979503 |edition=2nd |page=464}}</ref> <syntaxhighlight lang="c"> // 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 </syntaxhighlight> 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: <syntaxhighlight lang="c"> // 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) { ... } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)