×

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

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in...

5 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Statements in java

What is Statement in java: A statement in java is an instruction that explains what will happen based on the condition. Types of java statements: There are different statements in java Expression statementDeclaration statementControl...

2 minutes read.

How to Reduce Time Complexity in Java

What is time complexity?  The time complexity in java is given as the amount of time a program requires to run or execute it Calculating the time complexity of the program The time...

4 minutes read.

Java Numbers

We use primitive data types like byte, int, long, double, etc to work with the numbers, When we need objects, we use wrapper class like Integer, Double, Long, Byte, etc....

2 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

Add Time in Java

Before Java 8, java.util.Date was one of the most usually involved classes for addressing date-time values in java. Then Java 8 presented java.time.LocalDateTime and java.time.ZonedDateTime. Java 8 likewise permits us...

6 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Balanced Prime Number in Java

This section will cover the definition of a balanced prime number as well as how to find one using a Java program. Balance Prime Number A prime number that is equivalent to...

5 minutes read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

How to Iterate List in Java?

List is a Collection foundation interface in Java. It enables us to keep the collection of objects in order. The four classes that make up the List interface implementation are...

3 minutes read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.

String Coding Interview Questions in Java

What is String in Java?In Java, a String is a Class that is defined in the java.lang package. It isn't a basic data type like int or long. Character Strings...

5 minutes read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.