Encapsulation (object-oriented programming)

From LIMSWiki
Jump to navigationJump to search

Encapsulation is one of the four fundamentals of object-oriented programming (OOP), involving the concept of "bundling data with the methods that operate on that data."[1] Encapsulation places the values or state of a structured data object within a class, preventing unauthorized access to them. Publicly accessible methods are generally provided in the class (so-called "getters" and "setters") to access the values or state, and other client classes call these methods to retrieve and modify the values within the object. In some programming languages, this concept should not be interpreted as hiding; for example, in Java data can be encapsulated but also remain unhidden.[1] Additionally, encapsulation is not unique to object-oriented programming. Implementations of abstract data types like modules offers a similar form of encapsulation.

Definition

In programming languages, "encapsulation" is used to refer to one of two related but distinct notions (and sometimes to both)[2][3][4][1]:

  • a language mechanism for restricting access to some of the object's components
  • a language construct that facilitates the hiding of data with the functions operating on that data

Some programming language researchers and academics use the first meaning alone or in combination with the second as a distinguishing feature of OOP, while other programming languages which 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 OOP languages the placement 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.

As an information hiding mechanism

Under the second definition of "hiding," 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#, or Java) offer the programmer a degree of control over what is hidden, typically via keywords like public and private.[4] Note that the ISO C++ standard refers to protected, private, and public as "access specifiers" and that they do not strictly hide information.[5] 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.[6][7]

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();
    }
}

PHP offers a more simplistic approach[8]:

  • public - The method is publicly available and can be accessed by all subclasses.
  • protected - The method/function/property is available to the parent class and all inheriting classes.
  • private - The method is private and only available to the parent or base class.

Below is an example in PHP:

	class person {		
	var $name;		
		public $height;		
		protected $social_insurance;
		private $pinn_number;
		
		function __construct($persons_name) {		
			$this->name = $persons_name;		
		}		
		
		function set_name($new_name) {   	
			$this->name = $new_name;
		}	

		function get_name() {
			return $this->name;
		}		
			
	}

Encapsulation is also possible in older, 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);

Clients call the API functions to allocate, operate on, and deallocate objects of an opaque 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"

// 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)
{ ... }

Notes

This article reuses numerous content elements from the Wikipedia article.

References

  1. 1.0 1.1 1.2 Rogers, William Paul (18 May 2001). "Encapsulation is not information hiding". JavaWorld. http://www.javaworld.com/article/2075271/core-java/encapsulation-is-not-information-hiding.html. Retrieved 28 August 2014. 
  2. Scott, Michael Lee (2009). "Chapter 9: Data Abstraction and Object Orientation". Programming Language Pragmatics (3rd ed.). Morgan Kaufmann. pp. 449–500. ISBN 9780080922997. http://books.google.com/books?id=GBISkhhrHh8C&pg=PA449. Retrieved 29 August 2014. 
  3. Dale, Nell B.; Weems, Chip (2008). "Chapter 8: Object-Oriented Software Engineering". Programming and Problem Solving with Java (2nd ed.). Jones & Bartlett Publishers. pp. 394–451. ISBN 9780763734022. http://books.google.com/books?id=qBKO1b8CsNUC. Retrieved 29 August 2014. 
  4. 4.0 4.1 Pierce, Benjamin C. (2002). "Chapter 20: Recursive Types". Types and Programming Languages. MIT Press. pp. 265–280. ISBN 9780262162098. http://books.google.com/books?id=ti6zoAC9Ph8C. Retrieved 29 August 2014. 
  5. "ISO/IEC JTC 1/SC22 N3690" (PDF). ISO. 15 May 2013. pp. 238–239. https://isocpp.org/files/papers/N3690.pdf. Retrieved 29 august 2014. 
  6. Yaiser, Michelle (31 October 2011). "Object-oriented programming concepts: Encapsulation". Adobe Systems Incorporated. http://www.adobe.com/devnet/actionscript/learning/oop-concepts/encapsulation.html. Retrieved 29 August 2014. 
  7. Patterson, Chris (3 January 2014). "Separating Concerns – Part 2: Services". Los Techies. http://lostechies.com/chrispatterson/2014/01/03/separating-concerns-part-2-services/. Retrieved 29 August 2014. 
  8. Achour, Mehdi; Betz, Friedhelm; Dovgal, Antony; Lopes, Nuno; Magnusson, Hannes; Richter, Georg; Seguy, Damien; Vrana, Jakub (29 August 2014). "PHP: Visibility". PHP Manual. The PHP Group. http://php.net/manual/en/language.oop5.visibility.php. Retrieved 29 August 2014.