Encapsulation In Java

Encapsulation:

Binding of attributes and behaviors in a single container .In java language it can be achieved by 'class' keyword.

class:

'class' is container which is collection of variable and mathods (or) it is a blueprint of the object.
syntax:
class ClassName
{
list of variables;
..
..
list of methods()
{
..
..
}
..
..
}
in the above syntax class is keyword.
ClassName any userdefined name.

Variable:

Variable is an identifer whose value can can be changed.
example: int x=10;      x=20;
In java language these variable are classified into following types
  1. Local variable
  2. Global variable
  3. Formal variable
  4. Block variable
  • Local variable:
  • If any variable declare with in method or constructor.
  • Global variable
  • If any variable declare with in class or outside of the method or constructor.
  • Formal variable
  • If any variable declare with in method signature or constructor signature.
  • Block variable
  • If any variable declare with in block(if block ,for block ete..)
class Demo
{
int x; --> Global Variable
void show(int y) --> formal Varaible
{
int z; -->Local Variable
if()
{
int p; --> Block Variable
}
}
}
class Demo
{
int x; //Glabal Varaible
void show()
{
int y=10;//Local Variable
x=100;
System.out.println("x value is "+x);
System.out.println("y value is "+y);
}

void disp()
{
int z=20;//Local Variable
x=200;
System.out.println("x value is "+x);
//System.out.println("y value is "+y);
System.out.println("z value is "+z);
}
}
class LocalGlobal
{
public static void main(String args[])
{
Demo d=new Demo();
d.show();
d.disp();
}
}    
For more programs click here