• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Introduction » Interface in Java
Next →
← Prev

Interface in java with Example Programs

By Dinesh Thakur

Java interface use for achieving 100% abstraction because the interface only contains methods without any implementation or body. However, it has only abstract methods and constants (final fields). Any field declared inside the interface is public, static, and final by default, and any method is an abstract public method. It specifies what must do but not how. Once an interface is defined, the class implements an interface by implementing each method declared by the interface. Also, one class can implement any number of interfaces.

We’ll be covering the following topics in this tutorial:

  • Advantages of Interface
  • Defining Interface
  • Interface Explanation  
  • Implementing Multiple Interface
  • Extending an Interface in Java
  • Interface vs. Class
  • Interface Vs. Abstract Classes

Advantages of Interface

• Interfaces are easier to work with than inheritance because you do not have to worry about providing any implementation details in the interface.
• Interfaces facilitate multiple inheritance, which is not possible with classes.
• Interfaces allow objects of unrelated classes to be processed polymorphically.
• Interfaces are like class templates; we never build them to represent any object, only to run interference between OOP concepts and Java programs.

Defining Interface

An interface in Java defines as a class, but a keyword interface is used instead of the keyword class. It can contain either constant (final fields) or abstract method declarations or both. All the interface methods are public and abstract by default, and all the fields are public, static, and final by default. Its syntax is.

[public] interface InterfaceName {
   // constant variable declarations
   // abstract method declarations
}

The optional public access specifier specifies whether other classes and packages can use this interface or not. If the public access specifier omits, only the classes within its package can use the interface. The keyword interface indicates that an interface named Interface Name is defined. The rules for naming the interface are the same as that of valid Java identifiers. For example, to define the Shape interface, we write.

interface Shape {
  double area();
  double circumference();
}

Interface Explanation  

In much the same way that abstraction does, interface hides the intricate details of implementation and shows only the necessary functionality, but there is a big difference between them. The methods declared in the interface are all abstract, while, in abstraction, you can have a combination of abstract and non-abstract.

How to Implement an Interface

As interface provides nothing but abstract method declarations so you will have to implement those methods in your classes. Include the implements keyword as part of class definition followed by the name of the interface that you want to implement and implement all of the methods in the interface with the same signature specified in the interface declaration. If a class does not implement all of the interface methods, the class must declare itself as abstract. When a class implements an interface, you can think of the class as signing a contract with the compiler agreeing to implement all the interface methods or will declare itself abstract. The simplified form for implementing an interface by a class is

[accessspecifier] [modifier] class ClassName
implements InterfaceName {
   // provide implementation for method in interfaces
}

Here, access specifiers (such as public, private, protected) and modifiers (such as static) are the same as discussed previously. ClassName is the name of the class. It follows by the implements keyword, followed by the name of the interface, InterfaceName.
This name identifies the name of the interface whose methods are to implement. The body of this class contains definitions of all the methods included in the interface.

Now let us consider an example of the Rectangle class that implements the Shape interclass

Rectangle implements Shape {
  private double length ,breadth;
  public Rectangle(double l,double b){
  length == l; breadth == b;
 }
}
public double area(){ return length * breadth;}
public double circumference(){return 2 * (length+breadth);}

Note that the methods area() and circumference() declared in the interface Shape are defined public in the class Rectangle in which they implement. If you omit the keyword public from any of these methods, the code will not compile. The implementation of the interface’s method must not have an access specifier that is more restrictive than implicit in the abstract method declaration, and you cannot get less restrictive than the public.

How to Creating interface Reference

Once you have defined and implemented an interface, it’s now time to know how the variable of an interface type can call the classes’ methods that implement it polymorphically.
It is impossible to create an instance of an interface, as they do not provide an implementation for any methods that they declare, so to instantiate them will be completely illogical. However, you can create an object of a class that implements an interface and assign it to an interface reference variable. If you assign an object to the interface reference variable that does not implement that interface, the compiler will generate an error message.

For example, The statements

Shape s = new Rectangle (10,20) ;
System.out.println("Area of Rectangle == " + s.area());

The first statement creates a Rectangle object assigned to the reference variable s of Shape type. The second statement will print the area. The complete java interface example 

//use of interfaces
interface Shape {
 double area();// area method declaration
 double circumference();// circumference method declaration
 class Rectangle implements Shape {
 private double length,breadth;// Instance data
 public Rectangle(double l,double b){
   length = l; breadth = b;
 }
 public double area() { return length*breadth;}  
 public double circumference (){return2*(length+breadth);}
}
 class Circle implements Shape {
  public static final double PI =3.142;
  private double radius ;
  public Circle(double r){ radius = r;}
  public double area(){return PI*radius*radius;}
  public double circumference(){return 2 * PI * radius;}
 }
}
class InterfaceDemo {
 public static void main (String[] args){
 Shape[] s = new Shape[2];//Create an array to hold shapes
 s[0] = new Rectangle(10,20);//Assign rectangle object
 s[1] = new Circle(3);//assign circle object
 double total_area =0;
 for(int i = 0; i<s.length; i++){
   System.out.println("Area ="+s[i].area());
   //Compute circumference of shapes
   System.out.println("Circumference ="+s[i].circumference());
 }
}
}

Implementing Multiple Interface

A class can implement more than one interface. For this, you write all interfaces that the class implements separated by commas following the implements keyword. The class body must provide implementations for all of the methods specified in the interfaces. The syntax for implementing multiple interfaces is

[publicl class className [ extends superClassName]
 implements interface1, interface2, interfaceN {
   // Provide implementation for methods of
   // all included interfaces
   // ....................
}

In order to understand this let us consider a program.

// use of Multiple interfaces
// Interface one
interface Interface1 {
  void f1() ;
}
//Interface two
interface Interface2 {
  void f2();
}
class X implements Interface1,Interface2 {
  // definition of method declared in interface1
 public void f1() {
   System.out.println("Contents of method f1() in Interface1"); 
 }
  // definition of method declared in interface2
 public void f2() {
   System.out.println("Contents of method f2() in Interface2"); 
 }
 public void f3() {
   System.out.println("Contents of method f3() of class X"); 
 }
}
class Main {
  public static void main(String[] args) {
    Interface1 v1; //Reference variable of Interface1
    v1 = new X (); //assign object of class X
    v1.f1();
    Interface2 v2; //Reference variable of Interface2
    v2 = new X(); //assign object of class X
    v2.f2();
    X x1=new X();
    x1.f3();
  }
}

Output :

Contents of method f1() in Interface1 
Contents of method f2() in Interface2 
Contents of method f3() of class X

Explanation: In this program, two interfaces named Interface1 and Interface2, are defined. Interface1 contains method declaration of method f1(), and Interface2 contains method declaration of method f2(). Class x implements both these interfaces. So it provides the definitions of f1() and f2(). Besides, it also defines its method f3().

Multiple Interface in JavaExtending an Interface in Java

As I mentioned earlier, one interface can extend another but remember that an interface can’t implement any other interface; a class can only do that. The next example shows this extension in operation. We are using two interfaces – StaffNoDetails and EmployeeDetails, which will extend the StaffNoDetails class. First, we create the StaffNoDetails interface and give it one method called staffNo.

public interface StaffNoDetails {
 void staffNo();
}

Next, we create a different interface called EmployeeDetails. It will extend the StaffNoDetails and will have a name() method declared in it. Because the extends keyword has been used, the StaffNoDetails methods may now be inherited by EmployeeDetails; the latter interface will now have two methods – name() and staffNo().

public interface EmployeeDetails extends StaffNoDetails {
 void name();
}

A class called Details is created next, and this will implement EmployeeDetails. We must give both methods, name() and staffNo(), a body because the StaffNoDetails interface methods were inherited by the EmployeeDetails method. Details are also going to be the main class:

public class Details implements EmployeeDetails {
 public void name(){
   System.out.println("Dinesh Thakur");
 }
 public void staffNo(){
   System.out.println("0001");
 }
 public static void main(String[] args) {
    Details details =new Details();
    System.out.print("Name: ");
    details.name();
    System.out.print("Roll No: ");
    details.staffNo();
 }
}

The output of this will be:

Name: Dinesh Thakur
Roll No: 0001

Interface vs. Class

There are a few differences between interfaces and classes:
• An interface cannot instantiate whereas a class can.
• Every object created in an interface after implementation has identical states; in a class, every object has a state of its own.
• In an interface, objects must implement the defined contract to define their behavior; in a class, unless an object is overridden, all objects have the same behaviors.
• Interface variables are static public finals and, when defined, must have a value assigned. With a class, the variables are instance unless specified otherwise.
• Interfaces cannot inherit classes, but they can extend multiple interfaces. Classes can inherit only a single class and can implement multiple interfaces.
• Interface methods are public abstract and have no definition; in a class, every method must define unless the abstract keyword has been used as a decorator.

Interface Vs. Abstract Classes

Interfaces and abstract classes both implement polymorphic behavior and seem to be similar, but they are different in the following ways:
1. An interface is purely abstract, i.e., methods in an interface only have declarations no implementations. On the other hand, abstract class methods may or may not have an implementation.
2. A class implementing an interface must implement all of the methods declared in the interface. A class extending an abstract class needs not to implement any of the abstract class methods.
3. Abstract classes are used when there is an IS-A relationship between the classes. However, interfaces can be implemented by unrelated classes.
4. You can implement more that one interface, but you cannot extend more than one abstract class,
5. User-defined exceptions can be defined within an interface itself, which is not the case with the abstract class.
6. Members of an abstract class may have any access specifier modifier, but members of an interface are public by default and cannot have any other access specifier.
7. Abstract class definition begins with the keyword abstract followed by the class definition. On the other hand, the interface definition begins with a keyword interface.
8. All variables in an interface are public, static, and final by default, whereas an abstract class can have instance variables.
9. Abstract class does not support multiple inheritance, whereas the interface supports multiple inheritance.
10. If you define an interface and then later add a new method to an interface, you must implement that method in all of the classes that implement it. However, in an abstract class, you can safely add non-abstract methods to that class without requiring any modification to existing classes that extend the abstract class.
11. Interface is slow compared to the abstract class as they find the actual method in the corresponding classes.
12. Interface can extend another interface, whereas an abstract class can extend another class and implement multiple interfaces.
13. An abstract class can have constructors, but the interface cannot have constructors.

You’ll also like:

  1. Types of Java Programs
  2. What is Abstraction in Java? Abstract Class or Interface
  3. Java Interface Example
  4. Use of Interface in Java with Example
  5. Implementing Runnable Interface in Java Example
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW