Pages

Friday, 20 May 2022

Interface

An 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.

Interface looks like a class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signature, no body).

Also, the variables declared in an interface are public, static & final by default.

An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.

Note: A class implements interface but an interface extends another interface.

What is the use of interface in Java?

Interfaces are used for full abstraction. Since methods in interfaces do not have body, they have to be implemented by the class before you can access them. The class that implements interface must implement all the methods of that interface. Also, java programming language does not allow you to extend more than one class, However you can implement more than one interfaces in your class. An Interface is declared by specifying a keyword “interface”.

Internal addition by the compiler

The Java compiler adds public and abstract keywords before the interface method. Moreover, it adds public, static and final keywords before data members.


Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
(OR)
interface <interfaceName>
{
/* All the methods are public abstract by default
* As you see they have no body
*/
public abstract void method1(); 

public abstract void method2();

....
}
 

Ex1:
interface Iface
{
/* compiler will treat them as:
* public abstract void method1();
* public abstract void method2();
* even though we do not mention abstract
*/
public void method1(); 
public void method2();
}
class Demo implements Iface
{
/* This class must have to implement both the abstract methods
* else we will get compilation error
*/
public void method1()
{
System.out.println("This is implementation of method1");
}
public void method2()
{
System.out.println("This is implementation of method2");
}
public static void main(String arg[])
{
Iface x=new Demo(); 
x.method1();
x.method2();
}
}
Output:
C:\Users\Student\Desktop\java prg>javac Demo.java 
C:\Users\Student\Desktop\java prg>java Demo
This is implementation of method1
This is implementation of method2

Ex2:

// create an interface 
interface Language
{
void getName(String name);
}
// class implements interface
  class ProLang implements Language
  {
// implementation of abstract method 
public void getName(String name)
{
System.out.println("Programming Language: " + name);
}
  }
class Main
{
public static void main(String[] args)
{
ProLang l=new ProLang(); 
l.getName("Java");
}
}

Output:
Programming Language: Java

Relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface, but a class implements an interface.
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple inheritance.
Ex:
interface Printable
void print();
}

interface Showable
void show();
}

class TestMinhertance implements Printable,Showable
{
    public void print()
    {
    System.out.println("Hello");
    
    public void show()
    {
    System.out.println("Welcome");
    }     
    public static void main(String args[])
     {
TestMinhertance obj = new TestMinhertance(); 
obj.print();
obj.show();
     }
}

Output:
C:\Users\KANAKA RAJU\Desktop\java 9-5-22>javac TestMinhertance.java
C:\Users\KANAKA RAJU\Desktop\java 9-5-22>java TestMinhertance
Hello
Welcome

Interface and Inheritance
An interface can not implement another interface. It has to extend the other interface.
In the example given below, we have two interfaces Inf1 and Inf2. Inf2 extends Inf1 so If class implements the Inf2, it has to provide implementation of all the methods of interfaces Inf2 as well as Inf1.
Ex3:
interface Inf1
{
public void method1();
}
interface Inf2 extends Inf1
{
public void method2();
}
public class Demo implements Inf2
{
/* Even though this class is only implementing the
* interface Inf2, it has to implement all the methods
* of Inf1 as well because the interface Inf2 extends Inf1
*/
public void method1()
{
System.out.println("Message from method1");
}
public void method2()
{
System.out.println("Message from method2");
}
public static void main(String args[])
{
Demo obj = new Demo(); 
obj.method2();
}
}
Output:
I:\>javac Demo.java 
I:\>java Demo
Message from method2

Tag or Marker interface in Java
An interface which has no member is known as a marker or tagged interface, for example, Serializable, Cloneable, Remote, etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.
Ex: How Serializable interface is written? 
public interface Serializable
{
}

Nested Interface
An interface can have another interface within it, which is known as a nested interface. It is similar to nested classes.
Ex:
interface printable
{
    void print();
    interface MessagePrintable
    {
    void msg();
    }
}

Default Method in Interface
Since Java 8, we can have method body in interface. But we need to make it default method. 
Ex:
interface Drawable
{
void draw();
default void msg()
 {
 System.out.println("default method");
 }
}
class Rectangle implements Drawable
{
 public void draw()
 {
 System.out.println("drawing rectangle");
 }
}
class TestInterfaceDefault
{
 public static void main(String args[])
 {
 Drawable d=new Rectangle();
 d.draw();
 d.msg();
 }
}
output:
ubuntu@ubuntu:~$ javac TestInterfaceDefault.java
ubuntu@ubuntu:~$ java TestInterfaceDefault
drawing rectangle
default method

More Examples on Interface
In the following example, the Picture interface has 5 methods. Its implementation is provided by ShowPictures class. In a real scenario, an interface is defined by someone else, but its implementation is provided by different implementation providers. Moreover, it is used by someone else. The implementation part is hidden by the user who uses the interface.
Ex1:
interface Picture
{
public void birds();
public void animals();
public void men();
public void women();
public void nature();
}

class ShowPictures implements Picture
{
    public void birds()
    {
    System.out.println("This is implementation of birds Method");
    }
    public void animals()
    {
    System.out.println("This is implementation of animals Method");
    }
    public void men()
    {   
    System.out.println("This is implementation of men Method");
    }
    public void women()
    {
    System.out.println("This is implementation of women Method");
    }
    public void nature()
    {
    System.out.println("This is implementation of nature Method");
    }
}
 
class UseShowPictures
{
    public static void main(String arg[])
    {
    Picture p=new ShowPictures();
    p.birds();
    p.nature();
    }
}

Output:
ubuntu@ubuntu:~$ javac UseShowPictures.java
ubuntu@ubuntu:~$ java UseShowPictures
This is implementation of birds Method
This is implementation of nature Method
 
Ex2:
interface cal
{
int x=7;
public int sum(int x,int y);
public float mul(float f,float g);
}

class Useintf implements cal
{
    public int sum(int x,int y)
    {
    return x+y;
    }
    public float mul(float p,float q)
    {
    return p*q;
    }
    public static void main(String x[])
    {
    int k=6;
    useintf u=new useintf();
    System.out.println("Sum Of Numbers :"+u.sum(6,7));
    System.out.println("Product Of Numbers :"+u.mul(4,8)); k=k+u.x;
    System.out.println("Interface Variable Value is :"+k);
    }
}
Output:
ubuntu@ubuntu:~$ javac Useintf.java
ubuntu@ubuntu:~$ java Useintf
Sum Of Numbers :13
Product Of Numbers :32.0
Interface Variable Value is :13
 
Multiple Inheritance
==============
interface Printable
{
void print();
}

interface Showable
{
void show();
}

class MulInhr implements Printable,Showable
{
public void print()
{
System.out.println("Message From print method");
}
public void show()
{
System.out.println("Message from show method");
 
}
public static void main(String args[])
{
MulInhr obj = new MulInhr(); obj.print();
obj.show();
}
}

Multiple inheritance is not supported through class in java, but it is possible by an interface, why? Multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its implementation is provided by the implementation class.
Ex:

interface Printable
{
void print();
}

interface Showable
{
void print();
}

class TestMulInh implements Printable, Showable
{
public void print()
{
System.out.println("Message from Implimented print() method of Printable and Showable interfaces");
}
public static void main(String args[])
{
TestMulInh mi = new TestMulInh(); mi.print();
}
}

Interface inheritance
==============
A class implements an interface, but one interface extends another interface.

interface Printable
{
void print();
 
}
interface Showable extends Printable
{
void show();
}

class InfInh implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
InfInh ih = new InfInh(); ih.print();
ih.show();
}
}

Java 8 Default Method in Interface
========================
Since Java 8, we can have method body in interface. But we need to make it default method. Ex:
interface Drawable
{
void draw(); default void msg()
{
System.out.println("default method");
}
}

class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}

class TstInfDef
 
{
public static void main(String args[])
{
Drawable d=new Rectangle(); d.draw();
d.msg();
}
}

Java 8 Static Method in Interface
=======================
Since Java 8, we can have static method in interface. Ex:
interface Drawable
{
void draw();
static int cube(int x)
{
return x*x*x;
}
}

class Rectangle implements Drawable
{
public void draw()
{
System.out.println("Message from draw() method of Rectangle");
}
}

class TestInterfaceStatic
{
public static void main(String args[])
{
Drawable d=new Rectangle(); d.draw(); System.out.println(Drawable.cube(3));
}
}

What is marker or tagged interface?
An interface which has no member is known as a marker or tagged interface. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.

No comments:

Post a Comment

Servlet - JSP Programs

JSP(Java Server Pages) Programs : JavaServer Pages (JSP) is a Java standard technology that enables you to write dynamic data-driven pages f...