×

Interface in Java

 

Interface in Java

In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also implement multiple inheritance. All the methods in the Interface class are implicitly public and abstract.

A Java class can implement more than one interface (multiple interfaces). We can use an interface in a class by appending keyword “implements” after class name followed by the interface name.

Example

class Dog implements Animal

Java interface does not contain an implementation of methods; it only contains the signature of the method.

An interface is a 100 % abstracted class that has only abstract methods.

Since Java 8, Interfaces supported default and static methods only. Earlier versions of Java support private methods also.

Some important points about the interface are as follows.

  • The class provides body for the interface method.
  • Interface methods are abstract and public by default.
  • An interface never contains a constructor.
  • The interface declared inside the interface is known as the nested interface.

Declaration

interface  <interface name>
{
//constants declaration
//methods declaration
//default
}

Use of interface in java

In Java, interfaces are used for different motives like:

  • To achieve fully abstraction.
  • To achieve multiple inheritance in Java.
  • To implement abstraction.
  • To hide extra details and only show the essential information.
  • To provide security.
  • To achieve loose coupling.

To use multiple interfaces, separate every interface with a comma (,). Interfaces cannot be used to create objects.

Let’s have a look at below example.

Example1

interface  First
{
public void method1();
}
interface Second
{
public void method2();
}
class TestDemo implements First, Second
{
public void method1()
{
System.out.println("Text 1");
}
public void method2()
{
System.out.println("Text 2");
}}
class MyClass
{
public static void main(String[] args)
{
TestDemo obj=new TestDemo();
obj.method1();
obj.method2();
}}

Output

Text 1
Text 2

Real World example of interface

Example2

In this example, the Vehicle interface has only one method. Its implementation is provided by Car and Bike classes. In Java, an interface is defined by someone else, but its implementation is provided by different implementation providers. Moreover, it is used by someone else. In this process, the implementation part is hidden by the user who uses the interface.

interface Vehicle{ 
void run(); 
} 
//Implementation by second user 
class Car implements Vehicle{ 
public void run(){System.out.println("Car is running");} 
} 
class Bike implements Vehicle{ 
public void run(){System.out.println("Bike is running");} 
} 
//Using interface by third user 
class TestInterface{ 
public static void main(String args[]){ 
Vehicle obj=new Bike();//object is provided by method
obj.run(); 
}}

Output

Bike is running

Multiple inheritance by interface in Java

If an interface extends multiple interfaces, or a class implements multiple interfaces, it is known as multiple inheritance.

Example

interface Printable{ 
void printMsg(); 
} 
interface Showable{ 
void showMsg(); 
} 
class TestInterface2 implements Printable,Showable{ 
public void printMsg(){System.out.println("Get to the Safe zone");} 
public void showMsg(){System.out.println("Message Displayed");} 
public static void main(String args[]){ 
TestInterface2 obj = new TestInterface2(); 
obj.printMsg(); 
obj.showMsg(); 
 } 
}

Output

Get to the Safe zone
Message Displayed

Interface inheritance

Interfaces support the concept of inheritance. In Java, we can inherit an interface with another interface.

Let’s understand it with the help of TestInterface2 example.

Example

interface Printable{ 
void printMsg(); 
} 
interface Showable extends Printable{ 
void showMsg(); 
} 
class TestInterface2 implements Showable{ 
public void printMsg(){System.out.println("Get to the Safe zone");} 
public void showMsg(){System.out.println("Message Displayed");} 
public static void main(String args[]){ 
TestInterface2 obj = new TestInterface2(); 
obj.printMsg(); 
obj.showMsg(); 
 } 
}

Output

Get to the Safe zone
Message Displayed

 

One interface is inherited by another interface using the keyword “extends”. It is required to provide implementations for all methods required by the interface inheritance chain when a class implements an interface that inherits another interface. Let’s see an example that illustrates how one interface inherits other interfaces.

 // One interface can extend another.
interface Subject
{
void meth1();
void meth2();
}
// Marks interface now includes meth1() and meth2() -- it adds meth3()
interface Marks extends Student
{
void meth3();
}
// StudentDemo class can implement all methods of Subject and marks interface
classStudentDemo implements Marks {
public void meth1()
{
System.out.println("Implementing meth1().");
}
public void meth2()
{
System.out.println("Implementing meth2().");
}
public void meth3()
{
System.out.println("Implementing meth3().");
}
}
class Demo
{
public static void main(String arg[]) {
//creating obejct of StudentDemo class
StudentDemo ob = new StudentDemo();
ob.meth1();
ob.meth2();
ob.meth3();
}
}

Static Method in Interface

Interfaces support static methods. They can take places in interfaces.

See at below example.

interface Vehicle{ 
void run();
static int cube(int x){return x*x*x;} ; 
} 
class Car implements Vehicle{ 
public void run(){System.out.println("Car is running");} 
} 
class Bike implements Vehicle{ 
public void run(){System.out.println("Bike is running");} 
} 
class TestInterface{ 
public static void main(String args[]){ 
Vehicle obj=new Bike();
obj.run();
System.out.println(Vehicle.cube(7));
}}

Output

Bike is running
343

Marker or Tagged interface

An interface without any member is known as a marker or tagged interface, for example, Cloneable, Serializable, Remote, etc. These interfaces are used to provide some essential information to the JVM so that JVM may perform some useful operation.

Public interface Cloneable
{
}

Nested interfaces

We can declare another interface within the interface, such an interface is called as a member interface or nested interface.

interface Printable{ 
void printMsg();  
interface Showable{ 
void showMsg(); 
}}
It can be declared as public, private, or protected. If we need to declare an interface outside the enclosing scope, it must be qualified by the name of the class or interface of which it is a member. Below is an example demonstrating the use of nested interface:
 //Demo class contains a member interface.
class Demo
            {
            //difining a nested interface
            public interface NestedIf
            {
            booleanisNotNegative(int x);
            }
            }
//Demo2 class implements the nested interface.
Class Demo2 implements Demo.NestedIF
            {
            publicbooleanisNotNegative (int x)
                        {
                        return x<0 ? false : true;
                        }
            }
Class NestedDemo
{
            public static void main (String args [])
            {
            //using reference of the nested interface
            Demo.Nestedifnif = new Demo2();
            if(nif.isNotNegative(5))
            System.out.println("5 is not negative");
            if(nif.isNotNegative(-9))
                        System.out.println("This won't be displayed because it is negative");
            }
}

Note: On the above code, the Demo class defines a member interface called NestedIf, and that is declared public. Followed by Demo2 implements the nested interface by “implements Demo.NestedIf”.

Reason for using interface:

  • To fully abstract a class.
  • To support dynamic method resolution at run time.
  • By using interface, we can achieve multiple inheritance in java.
  • To achieve loose coupling.

Related Topics

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

Types of Statements in Java

In natural languages, statements and sentences are roughly equivalent. In general, statements are similar to valid English sentences. We will talk about a statement in Java and the different kinds...

11 minutes read.

Java Applications

The growth in technology is increasing rapidly, so some languages are used for developing them. Java is one such famous programming language which is having numerous applications. The Java Programming...

4 minutes read.

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

Java Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

How to compare three dates in Java?

While using the date and the time in Java, we occasionally have to compare the dates. Java does not compare dates the same way it compares the two numbers. Therefore,...

6 minutes read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.

Java Boolean compareTo() method

The compareTo() method of Java Boolean class compares the Boolean argument with the Boolean instance and returns integer value, zero, or negative 1, or positive 1 based on the result...

2 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.