Difference between Abstraction and Encapsulation in Java
What is abstraction in java?
In java, abstraction is approach that is used for representing the key characteristics of a class without providing 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:
//Abstract class abstract class Animal { // Abstract method public abstract void makeSound(); } //Subclass of the abstract class class Dog extends Animal { public void makeSound() { System.out.println("Woof!"); } } //Another subclass of the abstract class class Cat extends Animal { public void makeSound() { System.out.println("Meow!"); } } //Main class to demonstrate the usage of the abstract class public class Main { public static void main(String[] args) { Animal dog = new Dog(); dog.makeSound(); // Output: Woof! Animal cat = new Cat(); cat.makeSound(); // Output: Meow! } }
Explanation:
Basically, in this program Animal is a abstract class that defines an abstract method makeSound (), Dog and Cat are two subclasses of Animal that implement makeSound () method.
And in the main class we create instances of Dog and Cat and call their makeSound()
Methods. Since Dog and Cat are subclasses of Animal we can use an Animal reference to point to either a Dog or a Cat object.
Output:
Woof! Meow!
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?
In java or object oriented programming 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: with the help of encapsulation we can hide the internal state of an object from the outside world. And reduce the risk of data alteration by accident.
- Access control: In java, we can change the visibility of the data and methods of a class by using access modifier. For instance, we can declare a variable private to prevent access from outside the class or a method public to enable calling from the other classes.
- Information hiding: we can hide the class’s users from the implementation specifics by using encapsulation. This means that as long as we keep the same interface, we can modify the implementation of a class without having any impact on its users.
- 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 to avoid errors brought on by unintentional data alteration by preventing 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("Rohit"); emp.setAge(19); emp.setSalary(40000); // 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: Rohit Age: 19 Salary: 40000
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.
Difference between abstraction and encapsulation
Encapsulation | Abstraction |
Through the use of public methods and encapsulation, a class can only reveal the information that is absolutely necessary to the outside world. | A class can only divulge to the outside world the information that is absolutely necessary by using public methods and encapsulation. |
It provides data hiding and modularity to a program. | It is flexible and reduce the complexity of a program. |
It allows us to control the access to the data members of a class. | It allows us to focus on more essential features of class or object. |
It is achieved by using access modifier like private public and protected. | It is achieved by using abstract class, interfaces and abstract methods. |
It helps to hide the information and improve the security. | It provide the clear separation of problems and reduce complexity. |