Saturday, September 1, 2012

interfaces in Object Oriented Programming Language


interface
==========
Descriptive set of methods. Implements class needs to be implemented methods in interface.

Properties of interface:
=========================
Canot mark interface as final
Cannot instiate interface.
Default: Methods in interface are abstract
fields in interface are static and final.
interface can implement class.
interface can extend multiple interfaces.

Class Implementing Interface
============================
package com.oops;

interface Bike{

//final static fields as default
int Capacity=150;

//abstract  methods as default
public void speed();
public void price();
}
public class InterfaceExample implements Bike {

@Override
public void speed() {
System.out.println("Speed of Bike is 100 KMPH");

}

@Override
public void price() {
System.out.println("Price of Bike is 75K");

}

public static void main(String args[]){

InterfaceExample it=new InterfaceExample();
it.speed();
it.price();
}

}

Interface extends Multiple Interfaces

public interface Computer
{
   public void setBrandname(String name);
}

public interface Desktop extends Computer
{
   public void setProperty(String prop);
   public void viewProperty(String id);
}

public interface Laptop extends Computer
{
   public void setProcess(double process);
   public void setScreen(int size);
}

public interface Laptop extends Computer,Device{

statements
}

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