Interface in Java | Java - Interfaces | Interfaces in Java

Java does not support multiple inheritance, i.e., classes in java cannot have more than one superclass. But, a large number of real life applications require the use of multiple inheritance where we inherit methods and properties from several distinct classes. So, Java provides an alternate approach known as interface to support the concept of multiple inheritance. Although a java class cannot be a subclass of more than one superclass, it can implement more than interface.

An interface in Java is similar to a class. Like class, interfaces also contain methods and variables. But the methods of interfaces are only abstract methods and variables of interfaces are declared as constants (i.e. static and final fields).

In other words, an interface is a collection of constants and abstract methods, which must be implemented in the class that uses it. Java does not support multiple inheritance but where there is need to share common methods Java uses an interface.

Interface is used to achieve complete abstraction. Every interface in java is abstract by default. So, it is not compulsory to write abstract keyword with an interface.  In Java, interfaces are declared using the interface keyword.

 

Syntax:

interace Interfacename

{

declare constant fields

declare method abstract by default;

}

Here, interface is the keyword and InterfaceName is any valid java variable name ( like class name)

 

 Example:

interface student

{

static final int roll=101;

static final String name= “Rohit”;

void show();

}

 

Implementing Interfaces:

In Java, an interface is implemented by a class.  To use an interface in a class, the class must use the keyword, implements. A class can implement any number of interfaces in Java.

An interface is used as “superclass” whose properties are inherited by a class. A class can implement one or more than one interface by using keyword implements followed by a list of interfaces separated by commas.

 

Syntax:

class ClassName implements InterfaceName

{

Body of the class

}

 

Programming Example:

 

interface  A          // interace defined

{

void  Ashow();      // interace defined

}

interface B

{

void Bshow()

}

class AB implements A,B    //interface implemented

{

public void Ashow()

{

System.out.println(“ Hello”);

}

public void Bshow()

{

System.out.println(“ Welcome to Assam”);

}

}

class ABC

{

public static void main(String args[])

{

AB obj=new AB();

obj.Ashow();

obj.Bshow();

}

}




Post a Comment

0 Comments