Monday, November 15, 2021

Interface in Java

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

An interface can have methods and variables, but the methods declared in an interface are by default abstract.


  • Like abstract classes, interfaces cannot be used to create objects
  •  Interface methods do not have a body - the body is provided by the"implement" class
  • On implementation of an interface, you must override all of its methods
  • Interface methods are by default abstract and public 
  • Interface attributes are by default public, static and final
  • An interface cannot contain a constructor (as it cannot be used to create objects)

An interface is declared by using the interface keyword. A class that implements an interface must implement all the methods declared in the interface.

interface <interface_name>{ 

     // declare constant fields 

    // declare methods that abstract by default. 

} 

To implement an interface we use keyword: implements

Example:

// Java program to demonstrate working of interface.

import java.io.*;

// A simple interface

interface Inf

{

  // public, static and final

            final int a = 10;

            // public and abstract

            void display();

}

// A class that implements the interface.

class TestClass implements Inf

{

            public void display()

            {

                        System.out.println("Java");

            }

public static void main (String[] args)

            {

                        TestClass t = new TestClass();

                        t.display();

                        System.out.println(a);

            }

}




0 comments:

Post a Comment

Data Structures with C++



NET/SET/CS PG



Operating Systems



Computer Networks



JAVA



Design and Analysis of Algorithms



Programming in C++

Top