Wednesday, October 8, 2014

Interface

Interface


Interface is a collection of methods and variables. Let’s see its general syntax:

Access_specifier interface interface_name
{
Datatype variable_name = value; \\ can declare multiple variables.
Returntype method_name1 (list of parameters);
Returntype method_nameN (list of parameters); \\ can declare multiple methods.
}

Points to remember about Interface:

1.     Interface is used to achieve runtime polymorphism and multiple inheritance.
2.     By default, methods and variables are public. All methods should be declared as public.
3.     Methods of interface never contain the body-part.
4.     Variables of interface should be initialized in the interface.
5.     It doesn’t contain constructors, object initialization blocks and static initialization blocks.
6.     By default methods of interface are abstract methods, and variables are final and static.
7.     ‘Implements’ keyword is used to implement methods of interface.
8.     If any class implements the interface and doesn’t fulfil the body-part of all its methods then, it is necessary to declare that class as abstract class. One interface can’t implement another interface.
9.     One interface can extends another interface. And one class can implement more than one interfaces.

Example:   inter.java

interface person
{
      string getadd();
      string getname();
      int age();
}
abstract class inter implements person {
      int age() {
      // definition of method
}
string getname() {
      // definition of method
}
}

This class must be declared as abstract because it doesn’t contain all the methods of interface person. If you don’t want to declare the class as an abstract class then, whether you require all methods or not you should define all the methods of the interface.

Example of inheritance of interfaces:

interface A {
      Void fun ();
}
interface B extends A {
      Void fun1 ();
}
class C implements B,A
{
      public void fun() {
      // body-part, if require
}
public void fun1() {
      // body-part, if require
}
}

Here , one class c has implemented 2 interfaces. 
One more thing , a class can extends another class and implements interfaces at the same time. Like this:

class apple extends fruits implements sweetfruits
{
      // body-part
      // it requires to define methods of sweetfruits interface.
}





No comments:

Post a Comment