Saturday, September 1, 2012

Encapsulation in Java Programming


Encapsulation: is like information Hiding.
Hiding the properites and behaviors of object and allowing outside access via public methods.

Example for Encapsulation:
============================

EmpDetails.java:
package com.oops;

public class EmpDetails {

private int empid;
private String empname;

public void setEmpid(int id){
empid=id;
}

public int getEmpid(){
return empid;
}

public void setEmpName(String name){
empname=name;
}

public String getEmpName(){
return empname;
}
}

EncapsulationExample.java

package com.oops;

public class EncapsulationExample {

/**
* @param args
*/
public static void main(String[] args) {

EmpDetails emp1=new EmpDetails();
emp1.setEmpid(1);
emp1.setEmpName("First");

System.out.println("Employee details id: "+emp1.getEmpid()+" and name:"+emp1.getEmpName());

}

}

Output
==========
Employee details id: 1 and name:First

No comments:

Post a Comment

Thanks for your valuable comments