{"id":77024,"date":"2020-03-03T11:31:08","date_gmt":"2020-03-03T06:01:08","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=77024"},"modified":"2020-03-03T11:31:08","modified_gmt":"2020-03-03T06:01:08","slug":"java-encapsulation","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/","title":{"rendered":"Java Encapsulation &#8211; Master the Concept with Real-life Examples"},"content":{"rendered":"<p>The most adopted and popular programming language approach, structured programming approach, failed to show the desired results in terms of bug-free, easy-to-maintain, and reusable programs.<\/p>\n<p>The programming approach, Object-Oriented approach (OOP), offers a new and powerful way to cope with this complexity. The approach of OOP is based on various concepts that help achieve its goal to overcome the drawbacks of structured programming approaches.<\/p>\n<p>This article will introduce you to one of the most fundamental concepts in OOP that is Encapsulation in Java.<\/p>\n<p>Moving forth in this article, we are going to learn in detail about &#8211;<\/p>\n<ol>\n<li>What is Java Encapsulation?<\/li>\n<li>Encapsulation in the Real-World<\/li>\n<li>Encapsulation- A way to implement Abstraction<\/li>\n<li>Achieving Encapsulation in Java<\/li>\n<li>Advantages of Java Encapsulation<\/li>\n<\/ol>\n<h3>What is Java Encapsulation?<\/h3>\n<p>Encapsulation is one of the most powerful and fundamental concepts of Object-Oriented Programming. Encapsulation, in general, is the action of enclosing or binding something. In OOP, it is a way of combining both data and functions that operate on that data, into a single unit.<\/p>\n<p>In other words, we can define it as <strong>Encapsulation<\/strong> is the wrapping up of data and functions (methods that operate on the data) into a single unit (called class).<\/p>\n<p>There is a prohibition for direct access to the data. Functions (that combine with the data) are the only way to access data. These functions are the member functions or methods in Java. It basically creates a shield due to which the code or data cannot be accessed outside the shield.<\/p>\n<p>If you want to read data items in an object, you call the member function in the object. It will read the data item from the function and return the value to you. You can\u2019t access the data directly using the object. The data is hidden, so it is kept protected and safe from accidental alteration.<\/p>\n<p>Data and its methods are said to be encapsulated into a single entity.<\/p>\n<p><em><strong>Get to know more about <a href=\"https:\/\/techvidvan.com\/tutorials\/java-methods\/\">Java Methods<\/a> in detail with Techvidvan.<\/strong><\/em><\/p>\n<p>The following figure shows the illustration of the approach of Encapsulation:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/03\/Approach-of-Encapsulation-in-Java.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-77173\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/03\/Approach-of-Encapsulation-in-Java.jpg\" alt=\"Java Encapsulation Approach\" width=\"732\" height=\"637\" \/><\/a><\/p>\n<h3>Encapsulation in the Real-world<\/h3>\n<p>Let us now consider the analogy to encapsulation in the real-world. In a large organization, there are so many departments like Sales, Accounts, <a href=\"https:\/\/www.investopedia.com\/terms\/p\/payroll.asp\">Payroll<\/a>, Purchase, Production, etc. Each department has its own personnel or staff that maintain its data.<\/p>\n<p>Suppose an employee of the Production department wants to know the quantity of raw material that has been purchased for the next month. The employee would not be allowed to go through the data files of the Purchase dept.<\/p>\n<p>Rather he will have to issue a memo to the \u2018Purchase\u2019 department requesting for the required information. Then some employees of the Purchase dept will go through the data files of Purchase and send the reply with the asked information.<\/p>\n<p>This practice ensures that the users access the data accurately and the unexpert outsiders do not corrupt this data. Therefore we can say that the <strong>\u2018data and employees\u2019<\/strong> of the department encapsulate together into a single entity, the Department.<\/p>\n<p>Similarly, objects provide an approach to program organization while helping to maintain the integrity of the program data.<\/p>\n<h3>Encapsulation &#8211; A way to implement Abstraction<\/h3>\n<p>With the help of Encapsulation, we can apply data abstraction. Encapsulation hides the implementation details of the object.<\/p>\n<p>We can often achieve Encapsulation through data\/information hiding. Data\/Information hiding is the process of hiding all the unessential characteristics of an object and showing only the necessary details.<\/p>\n<p>The structure of the object, as well as the implementation of its methods, are invisible to users.<\/p>\n<p>In the above example of the department, the essential information of the departments is visible that is dept-name, dept-head, number-of-employees, etc. The secret information which is not essential is not visible that is dept-profit\/loss, stock, etc.<\/p>\n<p>This information is available only if there request through a proper channel example, issuing a memo, etc.<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/03\/Encapsulation-in-java.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-77174\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/03\/Encapsulation-in-java.jpg\" alt=\"Java Encapsulation\" width=\"541\" height=\"357\" \/><\/a><\/p>\n<h3>Achieving Encapsulation in Java<\/h3>\n<p>In order to achieve encapsulation in Java, we have to \u2212<\/p>\n<ul>\n<li>declare the variables of a class as <strong>private<\/strong>, so that they cannot be accessed directly from outside the class.<\/li>\n<li>provide setter and getter methods that are declared as <strong>public<\/strong>, to view and change the values of the variables.<\/li>\n<\/ul>\n<p><em><strong>Dive a little deep into the concept of <a href=\"https:\/\/techvidvan.com\/tutorials\/variables-in-java\/\">Java Variables<\/a> and know more about it.<\/strong><\/em><\/p>\n<p>Now, we will see the practical implementation of encapsulation in the following program:<\/p>\n<p><strong>Code to explain the concept of Encapsulation in Java:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.encapsulation;\n\npublic class Encapsulation\n{\n  \/\/Declaring the variables as private\n  private String techVidvanName;\n  private String techvidvanProfile;\n  private int techVidvanAge;\n\n  \/\/declaring 'public' Setter and Getter Methods\n  public void setName(String techVidvanName)\n  {\n    this.techVidvanName = techVidvanName;\n  }\n  public String getName()\n  {\n    return techVidvanName;\n  }\n\n  public void setProfile(String techVidvanProfile)\n  {\n    this.techvidvanProfile = techVidvanProfile;\n  }\n  public String getProfile()\n  {\n    return techvidvanProfile;\n  }\n\n  public void setAge(int techVidvanAge)\n  {\n    this.techVidvanAge = techVidvanAge;\n  }\n  public int getAge()\n  {\n    return techVidvanAge;\n  }\n\n  public static void main (String[] args)\n  {\n    Encapsulation obj = new Encapsulation();\n\n    \/\/ setting values of the variables through setter methods\n    obj.setName(\"Avina Garg\");\n    obj.setAge(22);\n    obj.setProfile(\"Research Analyst Intern\");\n\n    \/\/ Displaying values of the variables through Getter methods\n    System.out.println(\"Name of the employee: \" + obj.getName());\n    System.out.println(\"Age of the employee: \" + obj.getAge());\n    System.out.println(\"Profile of the employee: \" + obj.getProfile());\n  }\n}<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"code-output\">Name of the employee: Avina Garg<br \/>\nAge of the employee: 22<br \/>\nProfile of the employee: Research Analyst Intern<\/div>\n<p>In the above code, we have three variables or data members techVidvanName, techVidvanAge, and techVidvanProfile. We have created separate setter and getter methods for all the variables and used these variables inside the same methods.<\/p>\n<p>Setter methods set the value of the variable, while Getter methods are used to get or return the values.<\/p>\n<h3>Advantages of Java Encapsulation<\/h3>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/03\/Advantages-of-java-encapsulation.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-77184\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/03\/Advantages-of-java-encapsulation.jpg\" alt=\"Advantages of Java Encapsulation\" width=\"802\" height=\"420\" \/><\/a><\/p>\n<p>We have already seen how important and essential the concept of Encapsulation is in Object-Oriented Programming. There are more benefits of using Encapsulation in Java which we are going to discuss below.<\/p>\n<p><strong>1. Data Hiding<\/strong> \u2013 Encapsulation allows the programmer to hide the <em><strong><a href=\"https:\/\/techvidvan.com\/tutorials\/java-inner-class\/\">inner classes in Java<\/a><\/strong><\/em> and to give access only to the desired codes to the users. It also gives the facility to the developer to not allow the users to know how the data and variables are stored.<\/p>\n<p><strong>2. Getter and Setter Methods<\/strong> \u2013 We can access private members-only within the same class. A class that is present outside this class can not access the private data members. If you need to access these private variables, you have to use public<strong> \u201csetter\u201d<\/strong> and <strong>\u201cgetter\u201d<\/strong> methods.<\/p>\n<p><strong>3. Flexibility and Maintainability \u2013<\/strong> With the help of encapsulation, we can make the fields of the class as write-only (If we only define the setter methods in the class) or read-only (If we only define the getter methods in the class) according to our requirements. It enhances the flexibility and maintainability of the code.<\/p>\n<p>For e.g. in the above code, the implementation code of void setName (String name) and String getName() can be changed at any point in time.<\/p>\n<p><strong>4. Code Reusability \u2013<\/strong> It allows the programmer or a user to effectively use the existing code again and again.<\/p>\n<p><strong>5. Total Control \u2013<\/strong> A class can have total control over what is stored in its variables and fields.<\/p>\n<p><strong>6. Ease of Testing \u2013<\/strong> With encapsulation, the testing becomes very easy. So, it is much better for Unit testing.<\/p>\n<h3>Summary<\/h3>\n<p>Encapsulation is one of the core features of Object-Oriented Programming. This feature introduces the concept of \u2018Data hiding\u2019. Every Java programmer should know how to implement the concept of Encapsulation.<\/p>\n<p>Coming to the end of this article, we discussed the detailed and conceptual description of Java Encapsulation with the real-world example, so that you can easily relate it with the real world analogy.<\/p>\n<p>We also covered the program to implement the encapsulation in Java. We understood the advantages of using Encapsulation in our programs to make them more flexible and effective.<\/p>\n<p>Thank you for reading our article. Do share your feedback through the comment section below.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The most adopted and popular programming language approach, structured programming approach, failed to show the desired results in terms of bug-free, easy-to-maintain, and reusable programs. The programming approach, Object-Oriented approach (OOP), offers a new&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":77184,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[1938,1939,1940,1941,1942,1943,1944],"class_list":["post-77024","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-achieving-encapsulation-in-java","tag-advantages-of-java-encapsulation","tag-benefits-of-encapsulation-in-java","tag-encapsulation-in-java","tag-java-encapsulation","tag-java-encapsulation-example","tag-what-is-java-encapsulation"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Java Encapsulation - Master the Concept with Real-life Examples - TechVidvan<\/title>\n<meta name=\"description\" content=\"Get to know in detail about Java Encapsulation with the real-life example along with way to implement the encapsulation in Java &amp; its advantages in detail.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Encapsulation - Master the Concept with Real-life Examples - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Get to know in detail about Java Encapsulation with the real-life example along with way to implement the encapsulation in Java &amp; its advantages in detail.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-03-03T06:01:08+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/03\/Advantages-of-java-encapsulation.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Encapsulation - Master the Concept with Real-life Examples - TechVidvan","description":"Get to know in detail about Java Encapsulation with the real-life example along with way to implement the encapsulation in Java & its advantages in detail.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/","og_locale":"en_US","og_type":"article","og_title":"Java Encapsulation - Master the Concept with Real-life Examples - TechVidvan","og_description":"Get to know in detail about Java Encapsulation with the real-life example along with way to implement the encapsulation in Java & its advantages in detail.","og_url":"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-03-03T06:01:08+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/03\/Advantages-of-java-encapsulation.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Java Encapsulation &#8211; Master the Concept with Real-life Examples","datePublished":"2020-03-03T06:01:08+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/"},"wordCount":1182,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/03\/Advantages-of-java-encapsulation.jpg","keywords":["Achieving Encapsulation in Java","Advantages of Java Encapsulation","Benefits of Encapsulation in Java","Encapsulation in Java","Java Encapsulation","Java Encapsulation Example","What is Java Encapsulation"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/","url":"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/","name":"Java Encapsulation - Master the Concept with Real-life Examples - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/03\/Advantages-of-java-encapsulation.jpg","datePublished":"2020-03-03T06:01:08+00:00","description":"Get to know in detail about Java Encapsulation with the real-life example along with way to implement the encapsulation in Java & its advantages in detail.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/03\/Advantages-of-java-encapsulation.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/03\/Advantages-of-java-encapsulation.jpg","width":802,"height":420,"caption":"Advantages of Java Encapsulation"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/java-encapsulation\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Java Encapsulation &#8211; Master the Concept with Real-life Examples"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/77024","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=77024"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/77024\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/77184"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=77024"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=77024"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=77024"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}