Difference between Encapsulation and Abstraction
Abstraction: Abstraction means representing the
essential features without showing the background details.It lets you
focus on what the object does instead of how it does.For example: Mobile
phone has features calling,messaging etc.A user can call or
message without knowing technical details that how a call is
connected,how voice is transfered over the network etc.Thus, hiding
internal implementation datails and just highlighting the set of
services offered is called as Abstraction.
Abstraction in java is achieved through interface and abstract class and methods.
abstract class MobilePhone
{
public abstract call(int number);
public abstract sendMsg(int number,String msg);
}
Encapsulation: Binding data and its functionality together into a single unit so that it cannot be accessed directly from outside is called as
Encapsulation.
For Example:I have an account in SBI bank.I went to
the bank and ask my balance.They will happily tell me my
balance.Again,if i ask them to change my balance without withdrawing or
depositing any thing,Will they..?. No because i don't have direct access
to the property balance.Balance is private member of account class and
we cannot directly modify it without using public methods withdraw() or
deposit().This is encapsulation.
Encapsulation in java is achieved through class and access modifier
(mainly private ).Hiding data behind the methods is the central concept
of encapsulation.If a class has all its member variables private then it is called as tightly encapsulated class.
class EncapsulationTest
{
private int a;
private int b;
public int getA() { }
public int getB() { }
public int setA() { }
public int setB() { }
}
Advantages:
1) Security
2) Enhancement will become easy.
3) Improves modularity of the application.
Note: In the case of abstraction you are hiding the implementation details from the user and showing only the set of services offered whereas in the case of encapsulation you are hiding the data members from the rest of your code in the application.
No comments:
Post a Comment