What is an interface in Java?
Interface in java is a core part of the Java programming language and one of the ways to achieve abstraction in Java along with the abstract class. Even though the interface is a fundamental object-oriented concept; Many Java programmers think of Interface in Java as an advanced concept and refrain from using the interface from early in a programming career. At a very basic level interface in java is a keyword but same time it is an object-oriented term to define contracts and abstraction, This contract is followed by any implementation of Interface in Java. Since multiple inheritances are not allowed in Java, the interface is the only way to implement multiple inheritances at the Type level.
In this Java tutorial, we will see What is an interface in Java, How to use an interface in Java, and where to use the interface in Java, and some important points related to the Java interface. What is an interface in Java is also a common core Java question which people asked on various programming exams and interviews.
Interface in java is a core part of the Java programming language and one of the ways to achieve abstraction in Java along with the abstract class. Even though the interface is a fundamental object-oriented concept; Many Java programmers think of Interface in Java as an advanced concept and refrain from using the interface from early in a programming career. At a very basic level interface in java is a keyword but same time it is an object-oriented term to define contracts and abstraction, This contract is followed by any implementation of Interface in Java. Since multiple inheritances are not allowed in Java, the interface is the only way to implement multiple inheritances at the Type level.
In this Java tutorial, we will see What is an interface in Java, How to use an interface in Java, and where to use the interface in Java, and some important points related to the Java interface. What is an interface in Java is also a common core Java question which people asked on various programming exams and interviews.
Key Points about Interface in Java
In the last section, we saw What is an interface in Java and learned that interface provides abstraction in Java and its only way to achieve multiple inheritances at type level in Java. In this section, we will see some important properties of the interface in Java.
1. The interface in java is declared using a keyword interface and it represents a Type like any Class in Java. a reference variable of type interface can point to any implementation of that interface in Java.
Its also a good Object-oriented design principle to "program for interfaces than implementation" because when you use interface to declare reference variable, method return type, or method argument you are flexible enough to accept any future implementation of that interface which could be the much better and high-performance alternative of the current implementation.
Similarly calling any method on the interface doesn't tie you with any particular implementation and you can leverage the benefit of better or improved implementation over time. This maintenance aspect of the interface is also sought in various software design interview questions in Java.
1. The interface in java is declared using a keyword interface and it represents a Type like any Class in Java. a reference variable of type interface can point to any implementation of that interface in Java.
Its also a good Object-oriented design principle to "program for interfaces than implementation" because when you use interface to declare reference variable, method return type, or method argument you are flexible enough to accept any future implementation of that interface which could be the much better and high-performance alternative of the current implementation.
Similarly calling any method on the interface doesn't tie you with any particular implementation and you can leverage the benefit of better or improved implementation over time. This maintenance aspect of the interface is also sought in various software design interview questions in Java.
2) All variables declared inside interface is implicitly public final variable or constants. which brings a useful case of using Interface for declaring Constants. We have used both Class and interface for storing application wide constants and advantage of using Interface was that you can implement interface and can directly access constants without referring them with class name which was the case earlier when Class is used for storing Constants. Though after introduction of static imports in Java 5 this approach doesn't offer any benefit over Class approach.
3) All methods declared inside Java Interfaces are implicitly public and abstract, even if you don't use public or abstract keyword. you can not define any concrete method in interface. That's why interface is used to define contracts in terms of variables and methods and you can rely on its implementation for performing job.
4) In Java its legal for an interface to extend multiple interface. for example following code will run without any compilation error:
interface Session extends Serializable, Clonnable{ }
Here Session interface in Java is also a Serializable and Clonnable. This is not true for Class in Java and one Class can only extend at most another Class. In Java one Class can implement multiple interfaces. They are required to provide implementation of all methods declared inside interface or they can declare themselves as abstract class.
Example of the interface in Java
Java standard library itself has many inbuilt interfaces like Serializable, Cloneable, Runnable or Callable interface in Java. Declaring the interface is easy but making it correct in the first attempt is hard but if you are in the business of designing API then you need to get it right in the first attempt because it's not possible to modify interface once it released without breaking all its implementation. here is an example of declaring interface in Java :
interface SessionIDCreator extends Serializable, Cloneable{
String TYPE = "AUTOMATIC";
int createSessionId();
}
class SerialSessionIDCreator implements SessionIDCreator{
private int lastSessionId;
String TYPE = "AUTOMATIC";
int createSessionId();
}
class SerialSessionIDCreator implements SessionIDCreator{
private int lastSessionId;
@Override
public int createSessionId() {
return lastSessionId++;
}
}
public int createSessionId() {
return lastSessionId++;
}
}
In above example of interface in Java, SessionIDCreator is an interface while SerialSessionIDCreator is a implementation of interface. @Override annotation can be used on interface method from Java 6 onwards, so always try to use it. Its one of those coding practice which should be in your code review checklist.
When to use interface in Java?
The interface is the best choice for Type declaration or defining contract between multiple parties. If multiple programmers are working in the different modules of the project they still use each other's API by defining the interface and not waiting for actual implementation to be ready.
This brings us a lot of flexibility and speed in terms of coding and development. Use of Interface also ensures best practices like "programming for interfaces than implementation" and results in more flexible and maintainable code.
Though interface in Java is not the only one who provides higher-level abstraction, you can also use abstract class but choosing between Interface in Java and abstract class is a skill. The difference between Interface in Java and abstract class in java is also a very popular java interview question.
This brings us a lot of flexibility and speed in terms of coding and development. Use of Interface also ensures best practices like "programming for interfaces than implementation" and results in more flexible and maintainable code.
Though interface in Java is not the only one who provides higher-level abstraction, you can also use abstract class but choosing between Interface in Java and abstract class is a skill. The difference between Interface in Java and abstract class in java is also a very popular java interview question.
That's it for now on What is Interface in Java, specifics of Java interface, and How and when to use Interface in Java. The interface is key to write flexible and maintainable code. If you are not yet using the interface in your code then start thinking in terms of interfaces and use it as much possible. You will learn more about interfaces when you start using design patterns. many design patterns like decorator pattern, Factory method pattern or Observer design pattern makes very good use of Java interfaces.
Other Java tutorials you may like
23 comments :
interface is really beautiful concept introduced by Object oriented programming language and Java seems use it perfectly. there are several benefits of using Interface while coding like:
1) Interface offers protection with change in requirement or future enhancement.
2) By using interface you can leverage more powerful implementation as highlighted in this article.
3) Code written using interface looks clean and extensible.
4) Interface can speed up development process and facilitate communication between two different module even if they are not complete.
Now question is how to master art of interface ? any good book which teaches how to design systems in terms of interface ?
interface Parent
{
void show();
}
class Child implements Parent
{
public void show()
{
System.out.println("Child");
}
public String toString()
{
System.out.println("toString");
}
}
///main() method
{
Parent p=new Child();
p.toString();
}
//What will be the output and WHY?
//is Interface also extending Object class,but How?
I think the output will be: Child because the interface Parent is printing out Child in its implementation.
@Anonymous and @Prasanna, I think output should be "toString", as show() method is not called any where. As Prasanna pointed out this Child object so toString() from Child class will get called.
Now your second question "Does interface in Java extends Object class", which is indeed a good question.
Simple answer is No. interface in Java doesn't extend java.lang.Object class.
You could probably ask, how come p.toString() compiled? because as per Java language specification, interface implicitly declared methods corresponding to java.lang.Object with same signature, until, It is getting those methods from super interface or they are already explicitly declared on interface.
OOPS concepts in brief
Object-An object is a software bundle of related state(Color,Height etc) and behavior(Selection).An object stores its state in fields (variables) and exposes its behavior through methods (functions).Ex-Vehicle.
Class-Class is ma collection of objects.
Inheritance-Different kinds of objects often have a certain amount in common with each other. Cars,Bikes etc for example, all share the characteristics of vehicles (speed, gear).
class Student{
int rollno;
String name;
void insertRecord(int r, String n){ //method
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}//method
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:
class car extends vehicle {
}
Interface-interface is a group of related methods without definition i.e code in them. Ex- Buttons on a Remote act as Interface betweenTV and the viewer. A vehicles behavior, if specified as an interface, might appear as follows:interface Vehicle {
void changeGear(int newValue);
void speedUp(int increment);
}
To implement this interface, the name of your class would change (to a particular brand of vehicle, for example, such as car), and you'd use the implements keyword in the class declaration:
class car implements vehicle {
}
Package-A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer.
I will add another frequently asked question related to interface in java
Why you use interface in java if you can not define any method there?
Well in reality interface is key for flexible and reusable java program. Suppose an Employee objects needs to calculate its salary and
There are different kinds of employees e.g. Hourly, Daily, Monthly. Now how do you write code for that
1. Does your employee needs to know all these salary calculation method? Or every employee needs to know only know its type. Interface save you here.
Inheritance is good for code reuse, but it can cost flexibility, if not used correctly. It's very important for an Object Oriented designer to understand inheritance in Java quite well. Following are some of the strong and week points of Inheritance, I have learned in hard way, might help your readers :
1)Inheritance is great if all sub classes have same behavior, but it's burden if some functionality defined in super-class is applicable to all but and some functionality to only few.
2) Inheritance is inflexible, you can not provide new functionality at runtime. Your object functionality is defined at compile time by methods defined in that class, there is no way to configure object at runtime, that's where composition outscore Inheritance.
3) Inheritance is great for defining types, that too, you should use interface for declaring type. By implementing interface, an object becomes part of a family and can stand for them.
4) Always prefer Composition over Inheritance
@Anonymous, I suggest you to read Effective Java, Joshua Bloach has suggested some good use of interface in Java, one of them is use interface for declaring type, advantage? One object can represent multiple type because it can implement multiple interface. Another advantage is that using interface will lead you to program for interface than implementation, which is key to create flexible object oriented design in Java.
many there and the example one is Comparator interface.
Hi Javin, I have couple of questions related to interface in Java :
Can one interface extend other interface in Java? If Yes, when should we extend other interface, a real world programming example would be great.
Can one interface extend a class? if not, Why
Can we define method inside interface in Java? if not, why?
Why all variables are public final constant on interfaces? are they static as well?
Why we can not define instance variable inside interface in Java?
Is there a limit on how many method an interface can contain? I usually see interface with one method e.g. Runnable, Comparable etc, any reasoning behind these?
here it will print toString because here we don,t show method and child is in show method
so out put will be toString
Though I agree that using interface is great in terms of flexibility, but it also has few disadvantages. For example by coding Interface, you are restricted to methods declared on interface. One example, which I face, where I had to change the type from Map to ConcurrentHashMap, was putIfAbsent(), this method is only defined in ConcurrentHashMap, and not in java.util.Map. If a method accepts java.util.Map and you provide CHM, you can't use putIfAbsent() method. Though, with default method coming in Java 8, Map class is extended to provide few more key methods e.g. replace() and putIfAbsent() etc.
One more use of interface which i think you should include here. Although an interface cannot be instantiated but since it is a type, Java allows to write a method with a parameter of an interface type. That method parameter will accept any class that implements this interface.
For example, public interface Creator{}
This is a valid method - void createObject(Creator creator, Integer i) { // do something}
This method will accept parameter an object of the following class:
Class carCreator implements Creator {}
hi this is very nice article. I've one question.
In below code which from which interface "method()" method will be called.
interface Rollable {
void method();
}
interface bounceback
{
int BAR=9;
void rollaback_of_Rollable();
void method();
}
interface bounceback1 extends bounceback,Rollable
{
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---");
}
}
public class InterfaceDemo {
/**
* This class demonstrates the interface
*/
public static void main(String[] args) {
Demo demo=new Demo();
demo.rollaback_of_Rollable();
demo.method();
}
}
hai this is very nice.......i have one question.....
in Below code how to try and catch........
import java.io.*;
import java.lang.*;
interface ebcalc
{
final static int re=100;
public void get();
public void put();
public void ebdisp();
}
class detail
{
String cname,caddr;
int lmr,cmr,a,u,b,c;
float amt,amt1;
public void get()
{
try
{
DataInputStream d=new DataInputStream(System.in);
System.out.println("Enter Customer Name:");
cname=d.readLine();
System.out.println("Enter Customer Address:");
caddr=d.readLine();
System.out.println("Enter Last Month Reading:");
lmr=Integer.parseInt(d.readLine());
System.out.println("Enter Current Month Reading:");
cmr=Integer.parseInt(d.readLine());
}
catch(Exception e)
{
}
}
public void put()
{
System.out.println("Customer Name:"+cname);
System.out.println("Customer Address:"+caddr);
System.out.println("Last Month Reading:"+lmr);
System.out.println("Current Month Reading"+cmr);
}
}
class result extends detail implements ebcalc
{
public void ebdisp()
{
u=cmr-lmr;
if(u>0&&u<100)
{
amt=u*1;
}
else if(u>=100&&u<200)
{
a=u-100;
amt=(a*1.5f)+100;
}
else if(u>=200&&u<300)
{
b=u-200;
amt=(b*2)+100+150;
}
amt1=amt+re;
if(lmr<cmr)
{
System.out.println("No of units:"+u);
System.out.println("Calculated amt:"+amt);
System.out.println("Rent:"+re);
System.out.println("Total amt:"+amt1);
In JDK 8 interfaces are allowed to have a default implementation where as earlier versions of JDK does not allow. This is a major update to JDK after a long time. I think it's better to update this article now to keen in sync with latest changes.
Note that from Java 8 interface can have default and static methods. Which means a default implementation for a method can be given. Also static methods can be written which can be accessed using Interface_name.method_name.
@Nuwan and @infoj, that's true, Java 8 has allowed interface to contain some actual code to do the job as well, it has bring interface little closer to abstract class in my opinion.
Hi ,Can some one please provide a real time example on Abstract and Interface class with respect to any web application or webpage .
JAVA 8 have got some modification on Interface like deafult and static methods can be defined in an interface.Can we have a post based on that linked in this tutoarial?
hello @sikdar007, good suggestion, I'll update the article. Btw, I have blogged about default methods on interface on Java 8 already, you may want to check that article.
I'm still not confident, though this article is very informative. I have used interfaces in past but don't exactly know what was the purpose.
Can you please explain all the points with an example? That how generally understand things: a code snippet showing the implementation, and an example that reader can relate to or implement on their own.
Hello dd, if you have used JDBC then you know about some of the popular interface like Driver, Connection, ResultSet etc. You can write your code by using this interface without worrying about their implementation, which is done by vendors like MySQL has their own JDBC Driver JAR, Oracle will have their own. The Point is interface allowed you to create your code without actual implementation. Interface is like a contract, you work your part and other party work their part.
Post a Comment