Thursday 10 November 2016

INTERFACES:



    An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with a major difference that interfaces define only abstract methods and final fields. This means that interfaces do not specify any code to implement these methods and data fields obtain only contants.
    The syntax for defining an interface is:
interface interfacename
{
    variable declaration;
    methods declaration;
}
      interface is a keyword and interfacename is the name of the interface.
    Variables are declared as follows:
static final type variablename=Value;
     Methods are declared as follows:
return-type methodname(Parameter-list);
    Ex:interface Myinterface
{
          static final int val=100;
          static final String name=”Santosh”;
          void show();
          int sum(int x,int y);
        }
The class that implements this interface must define the code for the method.
    Difference between Class and Interface:

Class
Interface
The members of a class can be constant or variables.
The members of an interface are always declared as constant, i.e.,their values are final.
The class definition can contain the code for each of its methods. That is, the methods can be abstract or non-abstract.
The methods in an interface are abstract in nature, i.e., there is no code associated with them. It is later defined by the class that implements the interface.
It can be instantiated by declaring objects.
It cannot be used to declare objects. It can only be inherited by a class.
It can use various access specifiers like public,private or protected.
It can only use public access specifier.

   Extending Interfaces: An interface can be subinterfaced from other interfaces. This is achieved by using the keyword extends as shown below:
interface Item1
{
    int val=100;String name=”Item”;
}
interface Item2extends Item1
{
    void show();
}
It is also possible to combine several interfaces together into a single interface as shown below:
interface Item1 {
    int val=100;
    String name=”Item”;
}
interface Item2 {
    void show();
}
interface Item3extends Item,Item2 {
    …….
}
An interface can’t extend classes.
   Implementing Interfaces: Interfaces can be used as “superclasses” whose properties are inherited by classes as shown below:
class classname implements interfacename
{
    //body of the class
}
It is also possible that a class can extend another class while implementing interfaces:
class classname extends superclass implements interface1,interface2,….
{
    //body of the class
}
Ex:interface Data{
 int val=100;
 void show();
}
class Base{
 int a;
 Base(int x) {
  a=x;
 }
}
class Derive extends Base implements Data{
int b;
Derive(int x,int y) {
super(x);
b=y;
}
public void show() {
  System.out.println("Value : "+val+" A : "+a+" B : "+b);
 }
}
class Interface{
public static void main(String args[]) {
  Derive d=new Derive(10,20);
  d.show();
 }
}

No comments:
Write comments