Ad Home

Theme images by kelvinjay. Powered by Blogger.

Travel

Header Ads

Java

Selenium

UFT

Framework

General QA Concept

BDD

» » » Types Of Encapsulation In Java

Types of Encapsulation


In my last post here I have provided the concept of Encapsulation. In this post I will describe the different types of Encapsulation.



There are two types of Encapsulation present in java..
  • Tightly Encapsulated Class
  • Loosely encapsulated class(Normal class)

Tightly Encapsulated Class
If a class is having every variable declared as private then it is called tightly encapsulated class.


class test
{

private int age;
private double salary;
private int phoneNumber;

}
Loosely Encapsulated Class
if a class is having atleast one normal variable or any variable other than private,then it is called Loosely Encapsulated Class.


class test
{

int age;
private double salary;
private int phoneNumber;

}
lets see how it works in parent child relationship:
Encapsulation mode Code
Tightly Encapsulated
class test
{
Private int age;
private double salary;
private int phoneNumber;
}
Loosely Encapsulated
class abc extends test
{
String Address;
}
Tightly Encapsulated
class xyz extends test
{
private String Name;
}

In this above example the parent class test is having 3 private variable, hence the parent class is tightly Encapsulated class.
The class abc is extending test class hence it is having total 4 variables available with it in which one is normal variable(other than private)
Private int age;
private double salary;
private int phoneNumber;
String Address;
As the string is normal variable so it does not pass the condition to be Tightly Encapsulation rule 
With the same logic the xyz class when extending to test  is a tightly Encapsulated class.

Encapsulation mode Code
Loosely Encapsulated
class test
{
String Name;
}

Loosely Encapsulated
class xyz extends test
{
private String Name;
}
Loosely Encapsulated
class abc extends xyz
{
private String Name;
}




In the above example test is the parent class which is loosely encapsulated as Name variable is not declared  as private. so class xyz when extends to test , automatically becomes loosely Encapsulated class even though it is having one private variable. Now when abc extends to xyz which is already a loosely Encapsulated hence it becomes loosely encapsulated.

So the rule is if the parent is not tightly coupled, there is no child class exists who is tightly coupled.

«
Next
Newer Post
»
Previous
Older Post

No comments:

Leave a Reply