Abstraction vs Encapsulation in Java
What is abstraction in java?
Abstraction is a technique used in Java to convey a class's essential features without supplying the implementation in classes and interfaces. We can say that abstraction is a technique that is used to show essential things to the user and hide the detail.
For example:
When you drive a car you can only see the essential detail like brakes, staring wheel, accelerator and all the detail like background work of these things are hidden.
Java abstraction feature enables the creation of reusable code that may be modified for many scenarios. It enables programmers to declare a collection of properties and methods that a class must have without defining the specifics of how they should operate.
This allows for flexibility and modularity in code design since multiple classes can implement the same abstract class or interface in various ways.
Abstract class in Java
Java defines an abstract classes as a class that cannot be created on its own but can be used as a model for subclasses to increase its capabilities.an abstract class can have instance variables, concrete methods, and abstract methods.
It is expressed using the “abstract” keyword in the class definition.
Any methods containing the abstract keyword and no implementation is considered to be an abstract method.
An abstract classes subclasses are either required to implement all of its abstract methods or else they must be explicitly marked as abstract.
Additionally, an abstract class may include constructors, static mode and instance variables. It is unfinished and lacks implementations for some of its methods, so it cannot be constructed on its own.
When you wish to establish a common behaviour or structure for a collection of related classes but don't want to fully implement that behaviour within the abstract class itself, you can make use of abstract classes.
As an alternative, you leave some methods abstract and permit the subclasses to implement them on their own. This encourages code reuse and aids in maintaining consistency in your code design.
Code implementation
Program using abstract class how we can implement abstraction in java:
//program to find the area of rectangle and triangle using abstraction in java import java.util.Scanner; public class _5Assignment { public static void main(String args[]) { System.out.println("This Program will calculate the area of Triangle and Rectangle"); System.out.println("Enter the Height: "); Scanner sc = new Scanner(System.in); float h = sc.nextFloat(); System.out.println("Enter the Base or Width: "); float b = sc.nextFloat(); Area a = new Triangle(); a.cal(h,b); Area c = new Rectangle(); c.cal(h,b); a.display(); c.display(); } } abstract class Area { abstract void cal(float a1 , float b1); void display() { System.out.println("The Calculated Area for the Triangle and Rectangle: "); } } class Triangle extends Area { double a; void cal(float h, float b) { this.a = ((0.5)*h*b); } void display() { super.display(); System.out.println("The area of triangle is: "+a); } } class Rectangle extends Area { double a; void cal(float h,float b) { this.a = (h*b); } void display() { System.out.println("The area of Rectangle is: "+a); } }
Output:
This Program will calculate the area of Triangle and Rectangle Enter the Height: 12 Enter the Base or Width: 12 The Calculated Area for the Triangle and Rectangle: The area of triangle is: 72.0 The area of Rectangle is: 144.0
Feature of Abstraction in Java
As we all know abstraction is a very important feature of object oriented programming in java.
There are some features of abstraction in java:
- By removing the specifics of an object, abstraction enables us to concentrate on its key characteristics. This simplifies and makes our programme or code simpler to read and maintain.
- Java implement abstraction through abstract classes and interfaces. Methods that are have no implementation are called abstract methods, which are defined by abstract classes.
- Concrete classes must implement abstract classes and interfaces in order for them to function. This guarantees the modularity, flexibility and extensibility of our code.
- By using abstraction, it is possible to create a hierarchy of related classes that each implement the same set of abstract methods in a unique fashion. We can reuse the code in this way and prevent repetition.
- We can write code that is independent of any specific implementation thanks to abstraction. This increases the portability of our code and makes it simple for us to swap implementations as needed.
What is Encapsulation in java?
Encapsulation in java, is a process in which we merge the data and the behaviour into a single unit. In other words, the idea of merging data and behaviour into a single unit is known as Encapsulation. It provide a clear interface for dealing with the class while it shield user from the implementation specifics of the class.
In java, encapsulation is accomplished in java by controlling the visibility of a class data and methods with access modifier like public, private and protected.
Feature of encapsulation
There are some key feature of encapsulation in java:
- Data hiding: By using encapsulation, we can keep an object's internal state a secret from the outside world. and lower the chance of unintentional data modification.
- Access control: In Java, we can use access modifiers to alter the visibility of a class's data and methods. For example, we can define a function public to allow calling from other classes and a variable private to prohibit access from outside the class.
- Information concealment: Using encapsulation, we can shield class users from implementation-specific details. Basically it means we can change a class implementation without affecting the users if we maintain the same interface.
- Enhancement of maintainability: By eliminating interclass dependencies, encapsulation contributes to the improvement of our code's maintainability. This implies that we can modify a class's implementation without having an impact on the remainder of the programme.
- Improved security: Encapsulation contributes to our code's improved security by limiting access to a class's data and methods. It helps us so we can avoid error that occurs unintentional data alteration and we can prevent unauthorised access to the data.
Overall, encapsulation is an important concept in java that helps to improve the robustness, maintainability, and security of our code by hiding the implementation detail.
Code implementation
Let’s take a program to understand implementation of encapsulation in java:
public class Main { public static void main(String[] args) { Encapsulate emp = new Encapsulate(); emp.setName("Nikhar"); emp.setAge(19); emp.setSalary(22001); // Insted of direct calling variables we are calling getter and setters System.out.println("Name:"+emp.getName()); System.out.println("Age:"+emp.getAge()); System.out.println("Salary:"+emp.getSalary()); } } class Encapsulate { private String name; private int age; private int salary; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } }
Output:
Name: Nikhar Age: 19 Salary: 22001
Advantages of encapsulation
In java encapsulation provide number of benefits including some of the following:
- Modularity: By dividing a complex system into smaller, more manageable sections, encapsulation makes it simpler to develop modular programmes. Each component can be isolated within a separate class and only interact with other components of the system via well defined interfaces. As a result, maintaining and updating the code becomes simpler.
- Code Reusability: By making it simpler to construct and use class libraries, encapsulation encourages code reuse. Other programme elements can use a well-encapsulated class without needing to be aware of how it is internally implemented. This makes it simpler to write maintainable, effective code.
- Flexibility: Encapsulation offers flexibility in the internal implementation of the class. Changes to the internal implementation details won't have an impact on other portions of the programme as long as the public interface stays the same. This gives designers more freedom to build and improve the system over time.
- Testing and debugging: with the help of encapsulation we can test and debug a program very easily and we can separate faults to particular areas of the system. In return, difficulties can be resolved more quickly and with less difficulty.
Abstraction vs encapsulation in java
Feature | Abstraction | Encapsulation |
Definition | It helps us to reduce the complexity | Hide the internal detail and only show the public interface or essential information |
Usage | It is use for defining the set of behaviour | It is used for protecting the internal state of an object |
Mechanisms | It has abstract class and interface | It has access modifier like private, protected, and public |
implementation | It defines a contract or blueprint of behaviour that subclasses must implement | It restricts access to certain data or method that provide us public access through methods or interfaces |
Benefits | It also provide higher level of abstraction and it also reduce the complexity | It prevent unauthorized access and modification of data making code more secure and maintainable. |
Example | A shape is abstracted as a collection of methods like getArea () and getPerimeter () | A bank account balance is encapsulated as a private field and accessed through public methods like deposit and withdraw |