Saturday 4 March 2017

learn java encapsulation with example | getter setter

The Wrapping up of data and methods into a single entity(called class) is know as encapsulation. Data encapsulation is the most striking feature of a class in OOP. The data is not accessible to the outside world and old those methods, which are wrapped in the class can access it. These methods provides the interface between the objects and the program. This insulation of the data from direct access by the program is called data hiding.

Encapsulating data and corresponding methods(behaviors) into a single module is called encapsulation. if any java class follows data hiding and abstraction such type of class is said to encapsulated class.

        Encapsulation = Data hiding  + Abstraction 

Example:

class Account
{
private double balance;
public double getBalance()
{
 // validate user
return balance;
}
public void setBalance( double balance)
{
// validate user
this.balance=balance;
}
}

How to Achieve encapsulation in Java ?

              To achieve encapsulation in Java, In side a class, we declare all variables as private and to modify and access these variables data we use public getter() and setter() methods.The reason for using getters and setters instead of making your members public is that it makes it possible to change the implementation without changing the interface like in the above example.

Hiding Data behind methods is the central concept of encapsulation. The main Advantages of encapsulation are
  • We can achieve security 
  • Enhancement will become very easy
  • improves modularity of the application.

Tightly Encapsulated class

                A class is said to be tightly encapsulated if every data member declared as private. Whether the class contains getter and setter methods are not and weather those methods declared as public or not required to check.

Example:

class A
{
private int balance;
public int getBalance()
{
return balance();
}
}

References:

1.java complete reference
2. Programming with Java a Primer 3e By Balagurusamy
3.Core Java(TM), Volume I--Fundamentals
4.core java black book by nageswara rao
5.http://docs.oracle.com/javaee/6/tutorial/doc

0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top