Training Outcomes Within Your Budget!

We ensure quality, budget-alignment, and timely delivery by our expert instructors.

Share this Resource

Table of Contents

Interface in Java

The Java programming language is widely used across industries like the Internet of Things (IoT), Big Data, Blockchain and Artificial Intelligence, as it has always kept up with the market trends. While there are a bunch of things that make this programming language a developer favourite, an Interface in Java is one of its core concepts. It is a behavioural feature that helps describe the behaviour Classes that need to be implemented.

According to Oracle, Java is the number one programming language for today’s tech trends. The concept of Interface is a major contributing factor as it helps achieve multiple inheritances and abstraction. An Interface in Java specifies the Class's behaviour by providing an abstract type. Keep reading to understand more about how Interfaces work in Java.

Table of Contents

1) What is an Interface in Java?

2) What are the benefits of Interfaces?

3) How are Interfaces declared?

4) Nesting Interface in Java

5) What are examples of Interfaces?

6) Interface vs Class

7) Conclusion

What is an Interface in Java?

Object-Oriented Programming (OOP) involves a framework within which the Objects use Methods to establish their Interactions with the external world. These Methods shape the Object’s interaction with the external world. An Interface in Java is a collection of correlated Methods with empty bodies and a tool to achieve Abstraction. The Interface represents a Class in which the Constants are Static, and the Methods are Abstract.

An Interface in Java represents an ‘IS-A’ relationship. Similar to how an Abstract Class cannot be initiated, the Java Interface can also not be initiated. The reason behind an Interface being Abstract is because it only specifies what a Class should do and not how it should do it.

Syntax example of an Interface:
 

Interface {

    // declare constant fields
    // declare methods that abstract
    // by default.  
}

 

As shown in the example above, the keyword ‘Interface’ must be used in order to enable complete Abstraction. As a result, all existing Interface Methods are declared with an empty body, and all fields are Public, Static and Final by Default. Any Class implementing an Interface should also implement all existing Methods declared within the Interface using the keyword “Implements”.

The process of writing an Interface in Java is very similar to that of writing a Class. However, a Class outlines the Object’s behaviours and attributes, whereas an Interface has behaviours which a Class implements.

Java Programming
 

What are the benefits of Interfaces in Java?


Benefits of Java Interfaces
 

Interfaces in Java became capable of implementation in the release of Java 8, with ‘Static’ and ‘Default’ Methods being implemented in the ‘Interface’ definition. These updates in Java 8 were followed by the addition of ‘Private’ and ‘Private Static’ Methods. Therefore, an Interface in Java is capable of containing six various types of Methods.

Furthermore, implementing Interfaces in Java involves benefits such as Polymorphism, Abstraction and multiple Inheritances. Interfaces provide the following benefits:

1) Complete Abstraction: Complete Abstraction is a concept crucial to Object-Oriented Programming Methods. The primary benefits of Abstraction are easy implementation, simpler changes and smoother documentation. Hence, design becomes simpler, along with improved indexing and optimisation. Additionally, hiding a Method’s implementation from the end user eliminates unnecessary confusion.

2) Multiple Inheritance: Java Casses are capable of single Inheritance. This is where Interfaces come to the rescue by implementing multiple Inheritances, where a Class inherits the features of multiple Classes. The inherited Class has Fields and Methods which can be reused through Inheritance.

3) Loose Coupling: As the terms suggest, Loose Coupling in Java is where the Classes are independent of one another. There is lower interdependency and information flow between Classes in Loose Coupling. The Class becomes dependent on the Interface rather than the other Class. Moreover, dependencies between Classes must be passed externally during runtime rather than being hardcoded.

4) Polymorphism: Polymorphism is one of the basic features of any Object-Oriented Programming language. It is a concept where variables of different types can be used at different times. An example to substantiate this concept would be where a ‘Number’ Interface can take multiple forms like ‘RealNumber’, ‘WholeNumber,’ or ‘NaturalNumber’.

5) Code Semantics and Readability: Java Interfaces establish a declaration about the intentions of Methods and keep the concepts of Interface and Implementation separate.

Enhance your understanding of Java Enterprise Edition (EE) and learn to build Enterprise applications from scratch. Sign up for the Introduction to Java EE Training course now!

How are Interfaces declared?

Interfaces in Java are declared using the keyword ‘Interface’, which enables complete Abstraction. The definition of an Interface in Java has two parts: the Interface's body and the Interface's declaration. The many attributes of the Interface, like its name and information about whether it extends other interfaces, are all contained within the declaration. Furthermore, the constant and method declaration for that particular Interface is contained within the interface body. 

The syntax to declare an Interface is:
 

public interface {      

   // declare constant fields 

   // declare methods that abstract

   // by default. 

 

In the example above, the keyword ‘Public’ makes the Interface Public. This access specifier shows that the Interface is usable by another Class in any package. However, if the access specifier is not declared, the Interface access will be limited to only the Classes defined within the same package as the Interface.

The fields declared within the Interface body above are all Public, Static and Final by Default. Additionally, the Class must implement all the Methods declared in the Interface in the interaction. 

Nesting Interface in Java

The reason for applying the Nesting Interface method is the fact that the namespace conflicts are resolved by grouping all used interfaces or maybe by keeping related interfaces along with one class.

In the following illustration, interface embedding is the approach adopted. In this example, we print the prime numbers list using interface nesting.
 

//Interface Nesting

//Find First 10 Prime numbers

package InnerInterface;

public interface InterfaceOuter {

void display();

interface InterfaceInner {

void InnerMethod();

}

}

//class

package InnerInterface;

import InnerInterface.InterfaceOuter.InterfaceInner;

public class NestedInterface implements InterfaceInner {

public void InnerMethod() {

 int iteration = 0, num = 0, x = 1, y = 1;

while (num < 10) {

y = 1;

iteration = 0;

while (y <= x) {

if (x % y == 0)

iteration++;

y++;

}

if (iteration == 2) {

System.out.printf("%d ", x);

num++;

}

x++;

}

}

public static void main(String args[]) {

NestedInterface obj = new NestedInterface();

obj.InnerMethod();

}

}

Expected Output:

2 3 5 7 11 13 17 19 23 29

 

What are examples of Interfaces in Java?

Let’s take a look at some examples of Interfaces in Java:

Interface printable{  

void print();  

}  

class A6 implements printable{  

public void print(){System.out.println("Hello");}  

public static void main (String args[]){  

A6 obj = new A6();  

obj.print();  

 }  

}

 

In the Interface example code above, the Interface name is ‘printable’, followed by the Interface Implementation by Class A6. The program is designed to print the word ‘Hello’. It is to be noted that a Class can extend a Class and implement an Interface, and an Interface can extend another Interface.

Example #2 of an Interface in Java:
 

Interface A{
// members of A
}
Interface B{
// members of B
}
class C implements A, B{
// abstract members of A
// abstract members of B
}

The above example declares two Interfaces, A and B, which are implemented by Class C, which contains Abstract members of both A and B. This is the use-case where multiple Interfaces are implemented by one Class using the ‘Implements’ keyword.

Example #3 of an Interface in Java:
 

Interface Number{

// members of  Interface

}

Interface Sum extends Number {

               // members of Sum Interfac

              // members of Number Interface

}

 

The above example shows the Interface ‘Sum’ extending the Interface ‘Number’. This is the use-case where one Interface extends another Interface through the ‘Extends’ keyword.

Example #4 of an Interface in Java:
 

Interface A{

// …..

}

Interface B{

// ….. 

}

Interface C extends A, B{

//......

}

 

The above example shows how multiple Interfaces can be extended by one Interface, similar to how a Class can extend another Class. Although unlike a Class, an Interface can extend any number of other Interfaces. The declaration of this extension would simply include a list separated by commas of every Interface being extended.

Enhance your Web Development skills using Java and build dynamic web applications.

Sign up for the Web Development using Java Training course now!

Interface vs Class

Even though a class and an Interface are structurally alike, they are fundamentally distinct. The following are some of the significant differences between them:
 

Feature

Interface

Class

Inheritance

Can extend multiple interfaces

Can extend only one class

Implementation

Cannot contain method implementations

Can contain method implementations

Access modifiers

All methods are implicitly public

Methods can have various access modifiers

Constructors

Cannot have constructors

Can have constructors

Instantiation

Cannot be instantiated directly

Can be instantiated

Object type

Reference type for objects

Reference type for objects

Multiple inheritance

Supports multiple inheritance through interfaces

Does not support multiple inheritance

Extending

Extended using the 'extends' keyword

Extended using the 'extends' keyword

Keyword

Uses the 'interface' keyword

Uses the 'class' keyword

Usage

Used to define contracts for classes

Used to define blueprints for objects

Interface methods

All methods are implicitly abstract 

Methods can be abstract or concrete

 

Conclusion

Interface in Java is an essential tool to enable complete Abstraction in the code. They come into play by expanding on code capabilities by allowing Classes to be independent of one another. As a result, this decreases the inter-dependencies between the Classes too. The prime advantages of having Interfaces are to achieve multiple Inheritance and Polymorphism. Since the launch of Java 9, Static, Private, and Private Static Methods can also be contained within Interfaces.

If you would like to work on your Java basics or start afresh, sign up for the course on Java Basics for Beginners!

Frequently Asked Questions

What are benefits of Java? faq-arrow

Java offers platform independence, robustness, security, and scalability. With automatic memory management, rich standard library, and strong OOP support, it enables efficient development of diverse applications. Its active community and backward compatibility further enhance its appeal for developers across various domains.

What are four pillars of Java? faq-arrow

Platform independence, Object-Oriented Programming, Robustness and Security.

What are the other resources and offers provided by The Knowledge Academy? faq-arrow

The Knowledge Academy takes global learning to new heights, offering over 30,000 online courses across 490+ locations in 220 countries. This expansive reach ensures accessibility and convenience for learners worldwide.  

Alongside our diverse Online Course Catalogue, encompassing 17 major categories, we go the extra mile by providing a plethora of free educational Online Resources like News updates, Blogs, videos, webinars, and interview questions. Tailoring learning experiences further, professionals can maximise value with customisable Course Bundles of TKA
 

What is the Knowledge Pass, and how does it work? faq-arrow

The Knowledge Academy’s Knowledge Pass, a prepaid voucher, adds another layer of flexibility, allowing course bookings over a 12-month period. Join us on a journey where education knows no bounds. 

What are related Courses and blogs provided by The Knowledge Academy? faq-arrow

The Knowledge Academy offers various Java Courses, including Java Programming Course, JavaScript for Beginners Course and Hibernate Training Outline. These courses cater to different skill levels, providing comprehensive insights into Java Developer Objectives.

Our Programming & DevOps Blogs cover a range of topics offering valuable resources, best practices, and industry insights. Whether you are a beginner or looking to advance your Programming skills, The Knowledge Academy's diverse courses and informative blogs have you covered.
 

Upcoming Programming & DevOps Resources Batches & Dates

Date

building Java Programming

Get A Quote

WHO WILL BE FUNDING THE COURSE?

cross

OUR BIGGEST SPRING SALE!

Special Discounts

red-starWHO WILL BE FUNDING THE COURSE?

close

close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.

close

close

Press esc to close

close close

Back to course information

Thank you for your enquiry!

One of our training experts will be in touch shortly to go overy your training requirements.

close close

Thank you for your enquiry!

One of our training experts will be in touch shortly to go over your training requirements.