Difference between Abstraction and Encapsulation in Java with Examples
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Another way to think about encapsulation is, it is a protective shield that prevents the data from being accessed by the code outside this shield.
Technically in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of own class in which they are declared.
As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
Encapsulation can be achieved by Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.
Geek's name: Harsh Geek's age: 19 Geek's roll: 51
Data Abstraction is the property by virtue of which only the essential details are displayed to the user. The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviours of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects.
Shape constructor called Circle constructor called Shape constructor called Rectangle constructor called Circle color is Redand area is : 15.205308443374602 Rectangle color is Yellowand area is : 8.0
Difference between Abstraction and Encapsulation:
|Abstraction is the process or method of gaining the information.||While encapsulation is the process or method to contain the information.|
|In abstraction, problems are solved at the design or interface level.||While in encapsulation, problems are solved at the implementation level.|
|Abstraction is the method of hiding the unwanted information.||Whereas encapsulation is a method to hide the data in a single entity or unit along with a method to protect information from outside.|
|We can implement abstraction using abstract class and interfaces.||Whereas encapsulation can be implemented using by access modifier i.e. private, protected and public.|
|In abstraction, implementation complexities are hidden using abstract classes and interfaces.||While in encapsulation, the data is hidden using methods of getters and setters.|
|The objects that help to perform abstraction are encapsulated.||Whereas the objects that result in encapsulation need not be abstracted.|