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

Abstraction and Abstract Class in java


Abstraction: Abstraction is act of representing data without including background details.

In java it can be achieved by using abstract classes/interfaces.
Hiding information can be achieved by modifiers.

Example for Abstract method:
  abstract  void function();

Example of abstract class:
 abstract class TestAbstract{

   abstract void fun1();
   public void fun2(){
    statements
   }

abstract classes contain abstract methods and normal methods.

Abstract Class Example:
package com.oops;

abstract class Area{
int side;

Area(int a){
side=a;
}
abstract int area();
public void nonAbstractMethod(){
System.out.println("Non abstract Method");
}
}

class Square extends Area{

Square(int a) {
super(a);
}

@Override
int area() {

System.out.println("Square Area");
return side*side;
}

}

class Rect extends Area{

public Rect(int a) {
super(a);
// TODO Auto-generated constructor stub
}

@Override
int area() {
// TODO Auto-generated method stub
System.out.println("Area of Triangle");
return side*side;
}

}

public class AbstractClassExample {

public static void main(String args[]){

Square sq=new Square(3);
Rect rt=new Rect(5);

Area ar;

ar=sq;
System.out.println("Square Area"+ar.area());

ar=rt;
System.out.println("Rectangle area"+ar.area());
}
}

Output:
============
Square Area
Square Area9
Area of Triangle
Rectangle area25