Home Java Beginners Difference between Encapsulation and Abstraction in Java

 
 

Share on Google+Share on Google+

Difference between Encapsulation and Abstraction in Java

Advertisement
In this section we will discuss about the difference between Encapsulation and Abstraction in Java. Encapsulation is a process of hiding all the data and methods within a class from outside world. Abstraction on the other hand displays the essential features but hide the unnecessary features of an object.

In this section we will discuss about the difference between Encapsulation and Abstraction in Java. Encapsulation is a process of hiding all the data and methods within a class from outside world. Abstraction on the other hand displays the essential features but hide the unnecessary features of an object.

Encapsulation in Java is represented using  private, package-private and protected access modifier. It wraps the variables, method data and codes within a class into a single entity. The class and methods outside the wrapper cannot access the code and data defined under the wrapper. In encapsulation object becomes a container (or capsule) for related data variables and methods.

Abstraction in Java is represented by Interface, Abstract class, Abstract methods using "abstract" keyword. It hides certain details of the object that are not important and display that are essential. In deals with the outside view of an object (interface).

Encapsulation solves the problem in implementation level while the Abstraction solves the problem in the designing level.

Following is the example of Encapsulation:

public class Box
{
private int length;
private int width;
private int height;

public void setLength(int p)
{length = p;}

public void setWidth(int p)
{width = p;}

public void setHeight(int p)
{height = p;}

public int displayVolume()
{System.out.println(length*width*height)...
}

public static void main(String args [ ])
{
Box b1=new Box(3,4,5);
b1.displayvolume();
}

Following is the example of Abstraction:

abstract class A{
 public abstract abs_value();
 
 void show(){
 System.out.println("This is an abstract class");
 }
Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 13, 2013

Related Tutorials

Discuss: Difference between Encapsulation and Abstraction in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com