• iconJava Online Training In Andhra Pradesh and Telangana
  • icon9010519704

Opening Hours :7AM to 9PM

Java Interface

Java Interface

Interface is similar to class.It is used to achieve the multiple inheritance in java language.
Interface is replacement of abstract class.
Syntax:
interface InterfaceName
{
    public static final variable1;
    public static final variable2;
    ..
    ..
    abstract method1();
    abstract method2();
    ..
    ..
}

Every interface can be identify with interface keyword and represented by user defined name.

Defination of interface:
Interface is similar to class,Which is collection of public static final variables and abstract methods.
The main advantege with interface is common reusability that means these methods can be reused many number of classes with separate implementation part.
Interface always contains variable initilizations and abstract methods as shown below.

Example:
interface Demo
{
    int x=10; -> the signature is public static final int x=10;
    void show(); -> abstract void show();
    void disp();-> abstract void disp();
}

The properties of interface can be reuse any class with the help of implements keyword.

Syntax:
interface InterfaceName1
{
    returntype methodname1();
    ..
    ..
}

interface InterfaceName2
{
    returntype methodname2();
    ..
    ..
}

..
..

class classname implements  InterfaceName1,InterfaceName2,...
{
    accessmodifiers returntype methodname1()
    {
        Statement 1;
        Statement 2;
        ..
        ..
    }
    accessmodifiers returntype methodname2()
    {
        Statement 1;
        Statement 2;
        ..
        ..
    }
    ..
    ..
}

Every abstract method of interface should be overridden in the implemented class otherwise that class becomes abstract class.
Note:
If any abstract method is not overridden the derived class then that derived class also becomes abstract class(every abstract method should be overridden).
The main disadvantage in abstract class is it does not support multiple inheritance,so to overcome this problem we use interface.


MSK TechnologiesTrainings

Interface Program

interface Addition
{
    void add();
}
interface Substraction
{
    void sub();
}
class Demo implements Addition,Substraction 
{
    int x,y,z;
    public void add()
    {
        x=100;
        y=200;
        z=x+y;
        System.out.println("addition is "+z);
    }
    public void sub()
    {
        x=100;
        y=200;
        z=x-y;
        System.out.println("substraction is "+z);
    }
    void mul()
    {
        x=100;
        y=200;
        z=x*y;
        System.out.println("multiplication is "+z);
    }
}

public class Main
{
    public static void main(String args[])
    {
        Demo d=new Demo();
        d.add();
        d.sub();
        d.mul();
    }
}
                                

Output:
addition is 300
substraction is -100
multiplication is 20000