Tutorial

Interface in Java

Published on August 3, 2022
author

Pankaj

Interface in Java

Interface in java is one of the core concept. Java Interface is core part of java programming language and used a lot not only in JDK but also java design patterns. Most of the frameworks use java interface heavily.

Interface in Java

interface in java, java interface example Interface in java provide a way to achieve abstraction. Java interface is also used to define the contract for the subclasses to implement. For example, let’s say we want to create a drawing consists of multiple shapes. Here we can create an interface Shape and define all the methods that different types of Shape objects will implement. For simplicity purpose, we can keep only two methods - draw() to draw the shape and getArea() that will return the area of the shape.

Java Interface Example

Based on above requirements, our Shape interface will look like this. Shape.java

package com.journaldev.design;

public interface Shape {

	//implicitly public, static and final
	public String LABLE="Shape";
	
	//interface methods are implicitly abstract and public
	void draw();
	
	double getArea();
}

Important Points about Interface in Java

  1. interface is the code that is used to create an interface in java.

  2. We can’t instantiate an interface in java.

  3. Interface provides absolute abstraction, in last post we learned about abstract classes in java to provide abstraction but abstract classes can have method implementations but interface can’t.

  4. Interfaces can’t have constructors because we can’t instantiate them and interfaces can’t have a method with body.

  5. By default any attribute of interface is public, static and final, so we don’t need to provide access modifiers to the attributes but if we do, compiler doesn’t complain about it either.

  6. By default interface methods are implicitly abstract and public, it makes total sense because the method don’t have body and so that subclasses can provide the method implementation.

  7. An interface can’t extend any class but it can extend another interface. public interface Shape extends Cloneable{} is an example of an interface extending another interface. Actually java provides multiple inheritance in interfaces, what is means is that an interface can extend multiple interfaces.

  8. implements keyword is used by classes to implement an interface.

  9. A class implementing an interface must provide implementation for all of its method unless it’s an abstract class. For example, we can implement above interface in abstract class like this: ShapeAbs.java

    package com.journaldev.design;
    
    public abstract class ShapeAbs implements Shape {
    
    	@Override
    	public double getArea() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
    
    }
    
  10. We should always try to write programs in terms of interfaces rather than implementations so that we know beforehand that implementation classes will always provide the implementation and in future if any better implementation arrives, we can switch to that easily.

Java Interface Implementation Example

Now lets see some implementation of our Shape interface in java. Circle.java

package com.journaldev.design;

public class Circle implements Shape {

	private double radius;

	public Circle(double r){
		this.radius = r;
	}
	
	@Override
	public void draw() {
		System.out.println("Drawing Circle");
	}
	
	@Override
	public double getArea(){
		return Math.PI*this.radius*this.radius;
	}

	public double getRadius(){
		return this.radius;
	}
}

Notice that Circle class has implemented all the methods defined in the interface and it has some of its own methods also like getRadius(). The interface implementations can have multiple type of constructors. Lets see another interface implementation for Shape interface. Rectangle.java

package com.journaldev.design;

public class Rectangle implements Shape {

	private double width;
	private double height;
	
	public Rectangle(double w, double h){
		this.width=w;
		this.height=h;
	}
	@Override
	public void draw() {
		System.out.println("Drawing Rectangle");
	}

	@Override
	public double getArea() {
		return this.height*this.width;
	}

}

Notice the use of override annotation, learn about annotations in java and why we should always use override annotation when overriding a method in java. Here is a test program showing how to code in terms of interfaces and not implementations. ShapeTest.java

package com.journaldev.design;

public class ShapeTest {

	public static void main(String[] args) {
		
		//programming for interfaces not implementation
		Shape shape = new Circle(10);
		
		shape.draw();
		System.out.println("Area="+shape.getArea());
		
		//switching from one implementation to another easily
		shape=new Rectangle(10,10);
		shape.draw();
		System.out.println("Area="+shape.getArea());
		}

}

Output of the above java interface example program is:

Drawing Circle
Area=314.1592653589793
Drawing Rectangle
Area=100.0

Java Interface Benefits

  1. Interface provides a contract for all the implementation classes, so its good to code in terms of interfaces because implementation classes can’t remove the methods we are using.
  2. Interfaces are good for starting point to define Type and create top level hierarchy in our code.
  3. Since a java class can implements multiple interfaces, it’s better to use interfaces as super class in most of the cases.

Java Interface Disadvantages

Although interfaces provide a lot of advantages but it has some disadvantages too.

  1. We need to chose interface methods very carefully at the time of designing our project because we can’t add of remove any methods from the interface at later point of time, it will lead compilation error for all the implementation classes. Sometimes this leads to have a lot of interfaces extending the base interface in our code that becomes hard to maintain.

  2. If the implementation classes has its own methods, we can’t use them directly in our code because the type of Object is an interface that doesn’t have those methods. For example, in above code we will get compilation error for code shape.getRadius(). To overcome this, we can use typecasting and use the method like this:

    Circle c = (Circle) shape;
    c.getRadius();
    

    Although class typecasting has its own disadvantages.

Thats all I have for interface in java. Since we use java interface a lot, we should be aware of its features. Make sure you use interfaces in designing the system and as a contract between the client and the subclasses implementing the interfaces. Update: Java 8 has changed the definition of interfaces with the introduction of default methods and static methods implementation. For more details, please read Java 8 interface.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
May 18, 2014

Hi, This is very nice article. I 've one question. In below code from which version of the “method()” method called. interface Rollable { void method(); } interface bounceback extends Tyre { int BAR=9; void rollaback_of_Rollable(); void method(); } interface bounceback1 extends bounceback,Rollable,Tyre { abstract void rollaback_of_bounceback1(); public static final int BAR=10; void method(); } class Demo extends abclass implements bounceback1 { @Override public void rollaback_of_bounceback1() { System.out.println(“Method rollaback_of_bounceback1 BAR::”+BAR); } @Override public void rollaback_of_Rollable() { System.out.println(“Method rollaback_of_Rollable BAR::”+BAR); } static String method1() { return “Method method1_Demo BAR::”+BAR; } @Override public void method() { System.out.println(“--------Method ------------”); } // @Override //public void method() { //} } public class InterfaceDemo { /** * This class demonstrates the interface */ public static void main(String[] args) { Demo demo=new Demo(); demo.rollaback_of_Rollable(); demo.method(); }//end of method }//end of class

- maitrey

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
May 18, 2014

I don’t understood what is the confusion here, the only implementation of method() is in the Demo class.

- Pankaj

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
May 20, 2014

thank you for reply. Sorry for not giving proper question. I just want to clear one thing. “method()” is in Rollable,bounceback1,bounceback interface. so what happen in this scenario.

- maitrey

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    November 10, 2014

    Hi, Pankaj Can you explain that why the interface variable are public static and final???

    - Kumud

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    February 19, 2015

    class A{ A(int x){ SOP("arg is "+x); } } class Main{ pub. static void main(String a[]){ A a=new A(60); //calling to cont… } }

    - Mahadev

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      June 26, 2016

      First you should understand what does public static final means. Final keyword is used to tell compiler that this variable can’t change its value. And if we use final keyword before method it is to tell compiler that this method can’t be overloaded. You can read more about interface here https://thelearnerspoint.org/what-is-interface-in-java/

      - Khushboo singhal

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 1, 2014

        U will get error becoz ur not defined the interface Tyre and class abclass

        - Virupaksha

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        February 19, 2015

        explain only partial implemn of interface… plz

        - Mahadev Mane

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          September 25, 2014

          hi guyss…!!! i have some problem in java program … i’m student of BCA… can u plz give me the coding of this program… Q:- WAP for constructor with arguments in java…?? plz if u guyss have sufficient answer than plz rply me…:)

          - Guramandeep Kaur

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          September 25, 2014

          hey guraman … i have one problem in my question…!!! if u solve my problm then …i’ll solve ur problm …:P if u r agree with me …then plz rply…!!!

          - pooja chander

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          September 25, 2014

          sorryyy no idea … same ques. here…!!

          - manpreet kaur

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            November 26, 2014

            class Employee{ int id; String name; public void Employee(int id,String name){ this.id=id; this.name=name; } class Test{ public static void main(String[] args){ Employee emp=new Employee(123,“an\radya”); emp.id; emp.name; } }

            - anusha

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              May 21, 2015

              package com.myjava.constructors; public class MyParameterizedConstructor { private String name; public MyParameterizedConstructor(String str) { this.name = str; System.out.println(“I am inside parameterized constructor.”); System.out.println("The parameter value is: "+str); } public static void main(String a[]) { MyParameterizedConstructor mpc = new MyParameterizedConstructor(“Shashikant”); } }

              - Shashikant Kolwale

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                November 6, 2014

                thanks a lot !! you save my day!

                - Bruce

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  April 4, 2015

                  In important points: Interfaces can’t have constructors because we can’t instantiate them and interfaces can’t have a method with body. Confused with the above statement: If Constructors are depend on the instantiation, then why abstract class can contain constructors? Abstract class also cannot be instantiated.

                  - Raghuveer Kurdi

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 10, 2015

                  Note that constructors don’t actually create the object they just initialize the fields… Abstract class can have fields (which are not constants like in interface) so constructor is also valid.

                  - infoj

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    October 22, 2015

                    Thanks, your article is very useful and unique, because illustrates the reasons for using interfaces perfectly.

                    - Mohammed

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      December 14, 2015

                      In java, an interface is a blueprint of a class. It has provide only static constants and abstract methods in java.The interface is a mechanism to achieve fully abstraction. There can be only abstract methods in interface, not method body. An Interface is used to achieve fully abstraction and multiple inheritance in Java.Java Interface represents IS-A relationship. Interface is also not be instantiated just like abstract class.By default, Interface fields are public, static and final and methods are public abstract in java.

                      - RoyJain

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      October 2, 2016

                      But I used a Non-Abstract method in interface to create Multiple Inheritance.

                      - asha

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        October 2, 2016

                        PLS DO HELP ME!!!..It sayz “Shape is not abstract and does not override abstract method circum_circle() in Circle.”“” import java.util.*; import java.lang.*; interface Circle{ void area_circle(); void circum_circle(); } interface Square{ void area_square(); void circum_square(); } interface Rectangle{ void area_rect(); void circum_rect(); } class Shapes implements Circle,Square,Rectangle{ public void area_circle(int r){ double area=3.14*Math.sqrt®; System.out.println(“Area of Circle :”+ area); } public void circum_circle(int r){ double circum=6.28*r; System.out.println(“Circumference of Circle :”+ circum); } public void area_square(int a){ int area=a*a; System.out.println(“Area of Square :”+ area); } public void circum_square(int a){ int circum=4*a; System.out.println(“Circumference of Square :”+ circum); } public void area_rect(int l,int b){ int area=l*b; System.out.println(“Area of Rectangle :”+ area); } public void circum_rect(int l,int b){ int circum=2*l+b; System.out.println(“Circumference of Rectangle :”+ circum); } } class ShapesTest{ public static void main(String args[]){ Shapes sh=new Shapes(); sh.area_circle(3); sh.circum_circle(3); sh.area_square(4); sh.circum_square(4); sh.area_rect(10,20); sh.circum_rect(10,20); } }

                        - asha

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        October 2, 2016

                        You will have to implement Circle interface circum_circle() method in the Shapes class. If you are using Eclipse IDE, it will show error there also.

                        - Pankaj

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          January 31, 2017

                          Hi, Pankaj I dont understand interfaces! how does interfaces support code reusability when interface dont have any definition (only declaration) and the fact that anyways we’ve to write a definition in the class which we are using to implement interfaces ? why we need extra code of interface… and if we want to use the same behavior then we can call that method by creating that class object… please help me with proper example of interface… Thanks, Gandhimathi

                          - Gandhimathi

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            March 21, 2017

                            @Asha import java.util.*; import java.lang.*; interface Circle{ void area_circle(); void circum_circle(); } interface Square{ void area_square(); void circum_square(); } interface Rectangle{ void area_rect(); void circum_rect(); } class Shapes implements Circle,Square,Rectangle{ public void area_circle(int r){ double area=3.14*Math.sqrt®; System.out.println(“Area of Circle :”+ area); } public void circum_circle(int r){ double circum=6.28*r; System.out.println(“Circumference of Circle :”+ circum); } public void area_square(int a){ int area=a*a; System.out.println(“Area of Square :”+ area); } public void circum_square(int a){ int circum=4*a; System.out.println(“Circumference of Square :”+ circum); } public void area_rect(int l,int b){ int area=l*b; System.out.println(“Area of Rectangle :”+ area); } public void circum_rect(int l,int b){ int circum=2*l+b; System.out.println(“Circumference of Rectangle :”+ circum); } } class ShapesTest{ public static void main(String args[]){ Shapes sh=new Shapes(); sh.area_circle(3); sh.circum_circle(3); sh.area_square(4); sh.circum_square(4); sh.area_rect(10,20); sh.circum_rect(10,20); } } You have to implement all the unimplemented methods from all the interfaces. like … @Override public void area_rect() { } @Override public void circum_rect() { } @Override public void area_square() { } @Override public void circum_square() { } @Override public void area_circle() { } @Override public void circum_circle() { }

                            - APPPYA

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              August 1, 2017

                              nice very nice. keep writing thanks

                              - Anurag Singh

                                Try DigitalOcean for free

                                Click below to sign up and get $200 of credit to try our products over 60 days!

                                Sign up

                                Join the Tech Talk
                                Success! Thank you! Please check your email for further details.

                                Please complete your information!

                                Become a contributor for community

                                Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                DigitalOcean Documentation

                                Full documentation for every DigitalOcean product.

                                Resources for startups and SMBs

                                The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                Get our newsletter

                                Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                New accounts only. By submitting your email you agree to our Privacy Policy

                                The developer cloud

                                Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                Get started for free

                                Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                *This promotional offer applies to new accounts only.