☰ Topics

Encapsulation

It is generally wrapping of data or packaging of data. It is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. It only shows the relevant and hide the irrelevant information. In Java, the basis of encapsulation is the class.

We consider the program discussed in previous section i.e.

class exfun1
{
	public void add()   //Non-static function, object is needed to call
	{
		int num1=5,num2=6;   //input
		int sum=num1+num2;   //processing
		System.out.println("Sum="+sum);  //output
	}
	public static void main(String[] arg)
	{
		exfun1 ob=new exfun1();  //creation of object
		ob.add();  //invokation of function, dot is a referential operator used to call members of class
	}
}
                                    

OUTPUT:

E:\java\new_java>javac exfun1.java

E:\java\new_java>java exfun1
Sum=11
                                

In the above program, we can see that there is no code written inside main() method. Only the creation of object and invokation of method is done inside main() i.e. the functinality of add() is hidden from the user. Therefore, it increases the level of security. The level of security can also be increased by increasing the level of abstraction which is shown below by an example:-

class encaps
{
	public void fun()   
	{
		encaps ob=new encaps();  
		ob.add(); 
	}
	public void add()   
	{
		int num1=5,num2=6;   
		int sum=num1+num2;  
		System.out.println("Sum="+sum);  
	}
	public static void main(String[] arg)
	{
		encaps ob=new encaps();  
		ob.fun();  
	}
}
                            

OUTPUT:

E:\java\new_java>javac encaps.java

E:\java\new_java>java encaps
Sum=11

Moreover, we can also seperate the classes i.e. the functionality is defined in a class but the method is called from different class i.e. main() is defined in different class. In this case, we have to declare class as public. It is illustrated below:

public class encaps1
{
	public void add()   
	{
		int num1=5,num2=6;   
		int sum=num1+num2;  
		System.out.println("Sum="+sum);  
	}
}
     

class encaps_call
{
	public static void main(String[] arg)
	{
		encaps ob=new encaps();  
		ob.fun();  
	}
}
    

In this case, we need to compile only the class containing main(), all the related classes will automatically be compiled.
OUTPUT:

E:\java\new_java>javac encaps_call.java

E:\java\new_java>java encaps_call
Sum=11

Note:- Since java follows 100% OOPs features, therefore, we have to ensure that no code logic should be written main() function. It must be encapsulated inside another class. It enhances the security.