Tuesday, 22 August 2017

Interfaces in Java

An interface is like a class, which has methods and variable, but declared methods are by default abstract(means no method signature, no body). An Interface is also called blueprint of the class.

Points To Remember :


  • To declare an interface, we use "interface" keyword.
  •  It is used to provide total abstraction
  • All the methods in an interface are declared with an empty body are public and abstract by default 
  • All fields are public, static and final by default.

Syntax :


interface interface_name {
    
    // declare fields
    // declare methods
}

Why do we use interface?


  • It is used to achieve total abstraction.
  • Since Java does not support multiple inheritance in case of class, but it can be achieved by the use of an interface.
  • It is also used to achieve loose coupling.

Program to understand the concept of an interface :

interface A {
       int a=10; //by default public, static, final
      void display(); // by default public and abstract   
 }

class Demo implements A {
        public void display()
        {
           System.out.println("Hello world");
        }
       public static void main(String args[])
        {
            Demo obj = new Demo();
             obj.display();
             System.out.println(a);
         }
 }

OUTPUT:

Hello world
10




No comments:

Post a Comment