0% found this document useful (0 votes)
128 views10 pages

Understanding Java Encapsulation

1. Encapsulation in Java is a process that wraps code and data together into a single unit like a capsule containing medicine. 2. A fully encapsulated class has private data members and uses getter and setter methods to access the data from outside the class. 3. Encapsulation provides control over the data and achieves data hiding so that other classes cannot access private data members directly.

Uploaded by

Steward
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
128 views10 pages

Understanding Java Encapsulation

1. Encapsulation in Java is a process that wraps code and data together into a single unit like a capsule containing medicine. 2. A fully encapsulated class has private data members and uses getter and setter methods to access the data from outside the class. 3. Encapsulation provides control over the data and achieves data hiding so that other classes cannot access private data members directly.

Uploaded by

Steward
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
  • Encapsulation in Java
  • Write-Only and Read-Only Classes
  • Another Example of Encapsulation in Java
  • Abstraction Vs Encapsulation
  • Difference Between Abstraction and Encapsulation

Encapsulation in Java

Encapsulation in Java is a process of wrapping code and data together into a single unit,
for example, a capsule which is mixed of several medicines.

We can create a fully encapsulated class in Java by making all the data members of the
class private. Now we can use setter and getter methods to set and get the data in it.

The Java Bean class is the example of a fully encapsulated class.

Advantage of Encapsulation in Java


By providing only a setter or getter method, you can make the class read-only or write-
only. In other words, you can skip the getter or setter methods.

It provides you the control over the data. Suppose you want to set the value of id
which should be greater than 100 only, you can write the logic inside the setter method.
You can write the logic not to store the negative numbers in the setter methods.

It is a way to achieve data hiding in Java because other class will not be able to access
the data through the private data members.

The encapsulate class is easy to test. So, it is better for unit testing.

The standard IDE's are providing the facility to generate the getters and setters. So, it
is easy and fast to create an encapsulated class in Java.

Simple Example of Encapsulation in Java


Let's see the simple example of encapsulation that has only one field with its setter and
getter methods.

File: [Link]

1. //A Java class which is a fully encapsulated class.  
2. //It has a private data member and getter and setter methods.  
3. package [Link];  
4. public class Student{  
5. //private data member  
6. private String name;  
7. //getter method for name  
8. public String getName(){  
9. return name;  
10. }  
11. //setter method for name  
12. public void setName(String name){  
13. [Link]=name  
14. }  
15. }  

File: [Link]

1. //A Java class to test the encapsulated class.  
2. package [Link];  
3. class Test{  
4. public static void main(String[] args){  
5. //creating instance of the encapsulated class  
6. Student s=new Student();  
7. //setting value in the name member  
8. [Link]("vijay");  
9. //getting value of the name member  
10. [Link]([Link]());  
11. }  
12. }  
Compile By: javac -d . [Link]
Run By: java [Link]

Output:

vijay

Read-Only class
1. //A Java class which has only getter methods.  
2. public class Student{  
3. //private data member  
4. private String college="AKG";  
5. //getter method for college  
6. public String getCollege(){  
7. return college;  
8. }  
9. }  

Now, you can't change the value of the college data member which is "AKG".

1. [Link]("KITE");//will render compile time error  

Write-Only class

1. //A Java class which has only setter methods.  
2. public class Student{  
3. //private data member  
4. private String college;  
5. //getter method for college  
6. public void setCollege(String college){  
7. [Link]=college;  
8. }  
9. }  

Now, you can't get the value of the college, you can only change the value of college
data member.

1. [Link]([Link]());//Compile Time Error, because there is no such metho
d  
2. [Link]([Link]);//Compile Time Error, because the college data member is 
private.   
3. //So, it can't be accessed from outside the class  
Another Example of Encapsulation in Java
Let's see another example of encapsulation that has only four fields with its setter and
getter methods.

File: [Link]

1. //A Account class which is a fully encapsulated class.  
2. //It has a private data member and getter and setter methods.  
3. class Account {  
4. //private data members  
5. private long acc_no;  
6. private String name,email;  
7. private float amount;  
8. //public getter and setter methods  
9. public long getAcc_no() {  
10.     return acc_no;  
11. }  
12. public void setAcc_no(long acc_no) {  
13.     this.acc_no = acc_no;  
14. }  
15. public String getName() {  
16.     return name;  
17. }  
18. public void setName(String name) {  
19.     [Link] = name;  
20. }  
21. public String getEmail() {  
22.     return email;  
23. }  
24. public void setEmail(String email) {  
25.     [Link] = email;  
26. }  
27. public float getAmount() {  
28.     return amount;  
29. }  
30. public void setAmount(float amount) {  
31.     [Link] = amount;  
32. }  
33.   
34. }  

File: [Link]

1. //A Java class to test the encapsulated class Account.  
2. public class TestEncapsulation {  
3. public static void main(String[] args) {  
4.     //creating instance of Account class  
5.     Account acc=new Account();  
6.     //setting values through setter methods  
7.     acc.setAcc_no(7560504000L);  
8.     [Link]("Sonoo Jaiswal");  
9.     [Link]("sonoojaiswal@[Link]");  
10.     [Link](500000f);  
11.     //getting values through getter methods  
12.     [Link](acc.getAcc_no()+" "+[Link]()+" "+[Link]()+" 
"+[Link]());  
13. }  
14. }  
Abstraction Vs Encapsulation
Java is an object-oriented programming language and it follows OOPs concepts. The
OOPs concepts include classes, objects, polymorphism, inheritance. There are two other
features of OOPs i.e. abstraction and encapsulation. They both seem very similar but
totally different in concept and implementation. The major difference between
abstraction and encapsulation is that abstraction hides the code complexity while
encapsulation hides the internal working from the outside world. In this section, we will
discuss abstraction and encapsulation and the differences between abstraction and
encapsulation in Java.

Abstraction
It is a feature of OOPs. It is used to hide the unnecessary information or data from the
user but shows the essential data that is useful for the user. It can be achieved by using
the interface and the abstract class. In interfaces, only the methods are exposed to the
end-user. The best example of abstraction is a TV remote. The user only interacts with
the outer interface that is nothing but keys. The user only knows which key to press for
what function.

Let's understand the abstraction through a Java program.

1. //abstract class  
2. abstract class Shape   
3. {  
4. //abstract method  
5. //note that we have not implemented the functionality of the method  
6. public abstract void draw();  
7. }  
8. class Circle extends Shape  
9. {  
10. //implementing functionality of the abstract method  
11. public void draw()   
12. {  
13. [Link]("Circle!");  
14. }  
15. }  
16. //main class   
17. public class Test   
18. {  
19. public static void main(String[] args)   
20. {  
21. Shape circle = new Circle();  
22. //invoking abstract method draw()  
23. [Link]();  
24. }  
25. }  

Encapsulation
It is also a feature of OOP. It is used to bind up the data into a single unit called class. It
provides the mechanism which is known as data hiding. It is an important feature of
OOPs. It prevents to access data members from the outside of the class. It is also
necessary from the security point of view.

Let's understand the abstraction through a Java program.

[Link]

1. //A Java class to test the encapsulated class Account    
2. public class EncapsulationDemo  
3. {    
4. public static void main(String[] args)   
5. {    
6. //creating instance of Account class    
7. Account acc=new Account();    
8. //setting values through setter methods    
9. acc.setAcc_no(7560504000L);    
10. [Link]("Mark Dennis");    
11. [Link]("md123@[Link]");    
12. [Link](500000f);    
13. //getting values through getter methods    
14. [Link](acc.getAcc_no()+" "+[Link]()+" "+[Link]()+" 
"+[Link]());    
15. }    
16. }   

[Link]

1. class Customer  
2. {    
3. //private data members    
4. private long cstmr_id;    
5. private String cstmr_name, cstmr_email;    
6. private float amount;    
7. //public getter and setter methods    
8. public long getAcc_no()   
9. {    
10. return acc_no;    
11. }    
12. public void setAcc_no(long acc_no)   
13. {    
14. this.acc_no = acc_no;    
15. }    
16. public String getName()   
17. {    
18. return name;    
19. }    
20. public void setName(String name)   
21. {    
22. [Link] = name;    
23. }    
24. public String getEmail()   
25. {    
26. return email;    
27. }    
28. public void setEmail(String email)   
29. {    
30. [Link] = email;    
31. }    
32. public float getAmount()   
33. {    
34. return amount;    
35. }    
36. public void setAmount(float amount)   
37. {    
38. [Link] = amount;    
39. }      
40. }    

Difference Between Abstraction and Encapsulation


Abstraction Encapsulation

Abstraction is a feature of OOPs that hides Encapsulation is also a feature of OOPs. It hides the code an
the unnecessary detail but shows the data into a single entity or unit so that the data can b
essential information. protected from the outside world.

It solves an issue at the design level. Encapsulation solves an issue at implementation level.

It focuses on the external lookout. It focuses on internal working.

It can be implemented using abstract It can be implemented by using the access modifiers (privat


classes and interfaces. public, protected).

It is the process of gaining information. It is the process of containing the information.

In abstraction, we use abstract We use the getters and setters methods to hide the data.


classes and interfaces to hide the code
complexities.

The objects are encapsulated that helps to The object need not to abstract that result in encapsulation.
perform abstraction.

Common questions

Powered by AI

Abstraction and encapsulation are both fundamental OOP concepts but differ primarily in their focus and implementation. Abstraction is concerned with hiding the complex implementation details and exposing only the necessary aspects of an object through interfaces and abstract classes. This allows a focus on what the object does rather than how it achieves it . Encapsulation, on the other hand, deals with bundling the data (variables) and code (methods) that operate on the data into a single unit or class, and restricting access to some components using access modifiers, thereby hiding the internal state and requiring all interactions to be performed through well-defined interfaces . Abstraction addresses issues at the design level by simplifying interactions with an abstract layer, while encapsulation handles implementation-level concerns by ensuring controlled data access .

Encapsulation enhances maintainability in large software systems by promoting modularity and decoupling. When classes are encapsulated, internal changes within a class do not affect other parts of the system as long as the interface remains consistent, allowing developers to modify implementation details without widespread impacts. Additionally, encapsulation reduces the risk of undesirable side effects by controlling how data is accessed and modified, ensuring a more predictable and stable system behavior. This separation of concerns supports scalability and eases debugging, as encapsulated modules can be independently developed, tested, and maintained .

Without encapsulation, developers might face challenges such as unintentional data modification and lack of data protection since fields would be exposed and could be changed directly. This could lead to issues with data integrity and security breaches, as any part of the program could incorrectly alter object states. Furthermore, maintaining consistency across an application can become difficult due to the lack of centralized control. Encapsulation mitigates these issues by restricting direct access to fields and enforcing the use of methods for data manipulation, ensuring that all changes are valid and standardized through a controlled interface .

Implementation of encapsulation in Java directly involves the use of access modifiers to protect and manage data access within a class. The typical access modifiers used are 'private', 'public', and 'protected'. 'Private' is used to restrict access to data members, ensuring that they cannot be accessed directly from outside the class. Public methods like getters and setters are then used to allow access to these private fields indirectly, facilitating controlled interaction with the object's data. 'Protected' can be used for package-level access and for subclasses .

Encapsulation in Java allows data protection by restricting direct access to class data members, leading to better control over data. This is achieved by making data members private and providing public setter and getter methods to access and modify them, ensuring data validity through controlled access (e.g., validating data before setting it). This approach also facilitates easier testing since each fully encapsulated class can be tested independently, often improving unit testing processes due to its defined interfaces for interaction .

Together, abstraction and encapsulation form the backbone of OOP in Java by promoting a clean separation between an object's interface and its implementation. Abstraction contributes by defining the outward-facing behavior of an object through interfaces and abstract classes, allowing developers to interact with objects through defined functionalities without needing to understand lower-level operations. Encapsulation supports this by ensuring that the data underlying these functionalities remain hidden and protected, accessible only through those defined interfaces. This allows for modular and scalable system designs where components can be developed, modified, and replaced independently, enhancing flexibility and robustness of the overall system .

Encapsulation contributes to data hiding by allowing the developer to make class data members private and inaccessible from outside the class except through specific public methods such as getters and setters. This ensures that data can only be modified or accessed in controlled ways, preventing unauthorized access or unintended modifications. Data hiding is crucial for security as it protects the internal state of an object from external interference, thereby shielding sensitive information and preventing data integrity issues .

Encapsulation can distinctly improve design level by ensuring that classes expose only relevant interfaces for use, simplifying interactions and reducing dependencies between components. By focusing on the essential actions a class should perform, rather than how it performs them internally, architects and designers can create clearer, more intuitive APIs. At the implementation level, encapsulation aids in controlling access to the internals of a class, allowing changes to internal data structures without affecting external code. This emphasizes the importance of defining clear contracts between different system parts, supporting better code organization, maintainability, and flexibility .

Encapsulation aids in data validation by enabling controlled access to class attributes through setters that can include rules for data validation before assignment. For instance, a setter method might include logic to ensure an ID is set to values only greater than a specific number or to prevent negative numbers . This in-line validation means errors can be caught early and ensures data integrity without needing extra validation logic elsewhere, maintaining a centralized control point for data quality within the class. This is preferable because it keeps data handling concise, maintainable, and consistent across the application .

A real-world analogy for abstraction in Java is a TV remote control. Users interact with the TV through the remote by pressing buttons, without needing to understand the underlying electronic circuits or signals being transmitted to operate the TV. The remote exposes only those functionalities that are necessary for users like changing channels, adjusting volume, etc., which mirrors how abstraction presents only the required interface for an object's use while hiding complex internal mechanics .

Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a single unit,
for example,
2. //It has a private data member and getter and setter methods.  
3. package com.javatpoint;  
4. public class Student{  
5.
1. //A Java class which has only getter methods.  
2. public class Student{  
3. //private data member  
4. private String co
Another Example of Encapsulation in Java
Let's see another example of encapsulation that has only four fields with its setter
29. }  
30. public void setAmount(float amount) {  
31.     this.amount = amount;  
32. }  
33.   
34. }  
File: TestAccount.
Abstraction Vs Encapsulation
Java is an object-oriented programming language and it follows OOPs concepts. The
OOPs concepts
14. }  
15. }  
16. //main class   
17. public class Test   
18. {  
19. public static void main(String[] args)   
20. {  
21
14. System.out.println(acc.getAcc_no()+" "+acc.getName()+" "+acc.getEmail()+" 
"+acc.getAmount());    
15. }    
16. }   
Acc
29. {    
30. this.email = email;    
31. }    
32. public float getAmount()   
33. {    
34. return amount;    
35. }    
36

You might also like