A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

Interface in Java

What is Interface?

What is Interface?

  • It is similar to class.

  • The interface is a mechanism to achieve fully-abstraction.

  • There are only abstract methods in the interface, not method body.

  • Interface has only static and final variables.

  • we have to provide a method body in that java class who implements the interface.

  • It is used to achieve fully abstraction and multiple inheritances in Java.

  • It contains only final variables, it means constants.

  • We can not create the object of an Interface just as abstract class.

  • An interface and its methods are implicitly abstract. You do not need to use the abstract keyword while declaring an interface or its methods.

  • All the methods in an Interface by default public.

  • In the Java 8, we can have default and static methods in an interface.

  • In the Java 9, we can have private methods in an interface.

Example of Interface in Java:-





package oops;
interface myInterface
{
   int add (int x,int y);
   int sub (int x,int y);
   int mul (int x,int y);
   int div (int x,int y);
 }

public class useinf implements  myInterface
{
     public static void main(String[] args)
     {
         useinf d = new useinf();
            int e=10;
            int f=20;

            System.out.println ("add method= "+d.add(e, f));
            System.out.println ("sub method= "+d.sub(e, f));
            System.out.println ("mul method= "+d.mul(e, f));
            System.out.println ("div method= "+d.div(e, f));
     }

    @Override
    public int add(int x, int y)
    {
        return x+y;
    }
 
    @Override
    public int sub(int x, int y)
    {
        return x-y;
    }

    @Override
    public int mul(int x, int y)
    {
        return x*y;    
    }

    @Override
    public int div(int x, int y)
    {
        return x/y;
    }
}


 

In Java language, an interface can be defined as a contract between objects on how to communicate with each other. Interfaces play a vital role when it comes to the concept of inheritance.

An interface defines the methods, a deriving class(subclass) should use. But the implementation of the methods is totally up to the subclass.

LEARN TUTORIALS

.

.