Thursday 4 February 2016

What is Interfaces in java

Interfaces in java:
===============

Interface:
-----------
1.interface contains only abstract methods i.e fully abstract.

2.The interface keyword is used to declare an interface

How to declare Interface:
--------------------------
/* File name : hello.java */
import java.lang.*;
//only one package statement
//Any number of import statements

public interface hello
{
   ;;;;;;
}

inside the interface whether you declare or not by default that become public abstract

void m1();=======>public abstract void m1();

Implementing Interfaces:
-------------------------------------

1.Classes are responsible to implement the interfaces.
2.A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

3.An interface can extend more than one interface.
4.An interface can also implement more than one interface at a time.

Example on interfaces:
-----------------------

package blog;

interface hello
{
void test1();
void test2();
void test3();
void test4();
}
//child class is responsible to provide implementation
//It is not completely implementing so declaring it as abstract class
abstract class HelloImpl implements hello
{
public void test1()
{
System.out.println("test1");
}

public void test2()
{
System.out.println("test2");
}
}

class HelloImplOne extends HelloImpl{
public void test3()
{
System.out.println("test3");
}

public void test4()
{
System.out.println("test3");
}
}


public class InterfaceDemo {

public static void main(String[] args) {

HelloImplOne helloImplOne = new HelloImplOne();
helloImplOne.test1();
helloImplOne.test2();
helloImplOne.test3();
helloImplOne.test4();

}


}

1 comment: