Encapsulation in java
Dictionary meaning of Encapsulation:
The condition of being enclosed.
Capsule refers to a small container which contains a dose of medicine.
Definition of Encapsulation:
Encapsulation is a process of wrapping code and data into a single unit.
Encapsulation in real world:
Let us take an example of a HR in a company. We communicate through HR not directly with the departments. HR is acting as a public interface here.
Encapsulation in programming:
Encapsulation is the way of declaring the data members as private and providing access to the data members through public methods (getter and setter methods). As private field can’t be access outside the class that means data is hiding within the class. That’s why encapsulation is also known as data hiding.
1. Main Concept behind encapsulation is ‘control over the data’. It is achieved using class and access modifier private, protected, public. Class is act as a container which contains code and data.
2. Factory pattern and Singleton pattern in Java are based on the concept encapsulation.
Advantages/Benefits of Encapsulation:
- 1. A read-only (immutable) or write-only class can be made.
- 2. Control over the data.
- 3. It helps in achieving high cohesion and low coupling in the code.
Polymorphism In Java
Polymorphism in real world:
Polymorphism means more than one forms. Water can be of in any form solid, liquid or gas.
Polymorphism in programming:
In java polymorphism is a way in which something behaves differently based on its call. Let us take the example of + operator and see the below example.
In the above example + operator behaves differently based on type of argument. When arguments are of integer type it acts as additional operator and when arguments are of String type it acts as concatenation operator.
In java an object which can pass two or more IS-A test. All objects in java are polymorphic in nature because they passed IS-A test at least for its own type and Object class type.
Types of polymorphism:
- Static/compile time polymorphism (by method overloading).
- Dynamic/run time polymorphism (by method overriding).