In the last tutorial we discussed abstract class which is used for achieving partial abstraction. Unlike abstract class an interface is used for full abstraction. Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user(See: Abstraction). In this guide, we will cover what is an interface in java, why we use it and what are rules that we must follow while using interfaces in Java Programming.
What is an interface in Java?
Interface looks like a class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signature, no body, see: Java abstract method). Also, the variables declared in an interface are public, static & final by default. We will cover this in detail, later in this guide.
What is the use of interface in Java?
As mentioned above they are used for full abstraction. Since methods in interfaces do not have body, they have to be implemented by the class before you can access them. The class that implements interface must implement all the methods of that interface. Also, java programming language does not allow you to extend more than one class, However you can implement more than one interfaces in your class.
Syntax:
Interfaces are declared by specifying a keyword “interface”. E.g.:
interface MyInterface { /* All the methods are public abstract by default * As you see they have no body */ public void method1(); public void method2(); }
Example of an Interface in Java
This is how a class implements an interface. It has to provide the body of all the methods that are declared in interface or in other words you can say that class has to implement all the methods of interface.
Do you know? class
implements
interface but an interfaceextends
another interface.
interface MyInterface { /* compiler will treat them as: * public abstract void method1(); * public abstract void method2(); */ public void method1(); public void method2(); } class Demo implements MyInterface { /* This class must have to implement both the abstract methods * else you will get compilation error */ public void method1() { System.out.println("implementation of method1"); } public void method2() { System.out.println("implementation of method2"); } public static void main(String arg[]) { MyInterface obj = new Demo(); obj.method1(); } }
Output:
implementation of method1
You may also like to read: Difference between abstract class and interface
Interface and Inheritance
As discussed above, an interface can not implement another interface. It has to extend the other interface. See the below example where we have two interfaces Inf1 and Inf2. Inf2 extends Inf1 so If class implements the Inf2 it has to provide implementation of all the methods of interfaces Inf2 as well as Inf1.
Learn more about inheritance here: Java Inheritance
interface Inf1{ public void method1(); } interface Inf2 extends Inf1 { public void method2(); } public class Demo implements Inf2{ /* Even though this class is only implementing the * interface Inf2, it has to implement all the methods * of Inf1 as well because the interface Inf2 extends Inf1 */ public void method1(){ System.out.println("method1"); } public void method2(){ System.out.println("method2"); } public static void main(String args[]){ Inf2 obj = new Demo(); obj.method2(); } }
In this program, the class Demo
only implements interface Inf2
, however it has to provide the implementation of all the methods of interface Inf1
as well, because interface Inf2 extends Inf1.
Tag or Marker interface in Java
An empty interface is known as tag or marker interface. For example Serializable, EventListener, Remote(java.rmi.Remote) are tag interfaces. These interfaces do not have any field and methods in it. Read more about it here.
Nested interfaces
An interface which is declared inside another interface or class is called nested interface. They are also known as inner interface. For example Entry interface in collections framework is declared inside Map interface, that’s why we don’ use it directly, rather we use it like this: Map.Entry
.
Key points: Here are the key points to remember about interfaces:
1) We can’t instantiate an interface in java. That means we cannot create the object of an interface
2) Interface provides full abstraction as none of its methods have body. On the other hand abstract class provides partial abstraction as it can have abstract and concrete(methods with body) methods both.
3) implements
keyword is used by classes to implement an interface.
4) While providing implementation in class of any method of an interface, it needs to be mentioned as public.
5) Class that implements any interface must implement all the methods of that interface, else the class should be declared abstract.
6) Interface cannot be declared as private, protected or transient.
7) All the interface methods are by default abstract and public.
8) Variables declared in interface are public, static and final by default.
interface Try { int a=10; public int a=10; public static final int a=10; final int a=10; static int a=0; }
All of the above statements are identical.
9) Interface variables must be initialized at the time of declaration otherwise compiler will throw an error.
interface Try { int x;//Compile-time error }
Above code will throw a compile time error as the value of the variable x is not initialized at the time of declaration.
10) Inside any implementation class, you cannot change the variables declared in interface because by default, they are public, static and final. Here we are implementing the interface “Try” which has a variable x. When we tried to set the value for variable x we got compilation error as the variable x is public static final by default and final variables can not be re-initialized.
class Sample implements Try { public static void main(String args[]) { x=20; //compile time error } }
11) An interface can extend any interface but cannot implement it. Class implements interface and interface extends interface.
12) A class can implement any number of interfaces.
13) If there are two or more same methods in two interfaces and a class implements both interfaces, implementation of the method once is enough.
interface A { public void aaa(); } interface B { public void aaa(); } class Central implements A,B { public void aaa() { //Any Code here } public static void main(String args[]) { //Statements } }
14) A class cannot implement two interfaces that have methods with same name but different return type.
interface A { public void aaa(); } interface B { public int aaa(); } class Central implements A,B { public void aaa() // error { } public int aaa() // error { } public static void main(String args[]) { } }
15) Variable names conflicts can be resolved by interface name.
interface A { int x=10; } interface B { int x=100; } class Hello implements A,B { public static void Main(String args[]) { /* reference to x is ambiguous both variables are x * so we are using interface name to resolve the * variable */ System.out.println(x); System.out.println(A.x); System.out.println(B.x); } }
Advantages of interface in java:
Advantages of using interfaces are as follows:
- Without bothering about the implementation part, we can achieve the security of implementation
- In java, multiple inheritance is not allowed, however you can use interface to make use of it as you can implement more than one interface.
Chetan says
Hi i gone through whole java tutorial and found all the concepts describe pretty good………………………..You have done good job………..keep it……………
Regards:
Chetan
Pankaj Dangar says
These tutorial is very useful for the Fresher so you have done good job…tq so much…
C Nageswara Reddy says
Hi,
I am learning from this tutorial. This is very good for beginners. You explained lot. Thanks.
suman singh says
Hi first of all Thanks & you have done a good job.I want some definition and explanation of proxies,object class,Event handling,swing concepts.
Mohamed says
Hi Bro,
Your 14 points has to be change.we can access Methods with same signature but different return type in two or more interfaces.
Thank you.
kavyashri says
the above content was very useful in understanding some basic concepts about interface in java.thanks a lot….
Raghav says
Hi Chaitanya,
Your articles and examples are very informative and useful.
I am following a lot of these topics for understanding OOPS.
It has been very useful.
Thanks a lot.
Sanjaya Fernando says
This is a wonderful article. It gives all the details in short and sweet. Thank you very much. Well done guys.
Harsha says
All the interface methods are by default abstract and public and Variables declared in interface are public, static and final by default why??
Is there any particular reason for making them implicit,variable as final and static and methods as public and abstract.
Chaitanya Singh says
Hello Harsha,
Here are the answers to your questions:
Why interface variables are public, static and final? Since interface does not have a direct object, the only way to access them is by using a class/interface. That is why if interface variable exists, it should be static otherwise it wont be accessible at all to outside world. Now since it is static, it can hold only one value and any class that extends it can change the value, so to ensure that it holds a constant value, it has been made final. These are the reasons interface variables are static and final and obviously public.
Why interface methods are public and abstract? Interfaces are meant to define the public API of a type – and only that, not its implementation. So any method you define in an interface is by definition public and abstract.
bernadette says
can you give atleast 5 importance of user interface in java programs
Teja says
Hi, bernadette , the interface in java and the USER INTERFACE (UI) is completely different. Interface is a concept in java. Whereas , UI is a technology. I hope you got that!
surbhi sood says
can anyone please tell me the basic… first we have to make class in notepad?with .class extension
and then we have to write code for interface in different file?
kaushal says
write the code in notepad and save it as .java extension.
And u can write the class and interface in the same code.
then run your program using cmd . :-)
kiran says
I think point number 10 is incorrect..am able to change the variable in implementation class..Its not showing any errors..Plz reply me
Oshin Bakshi says
Hi Kiran,
Point 10 is correct see i give you an example:
interface i1
{
int x =10;
}
class xyz implements i1
{
int x =40;
void show()
{
int y = i1.x=60; // wrong because fields in interface is final
System.out.println(i1.x);
}
}
(i1.x=60)This is wrong because the variable x in interface i1 is final so if we change that value error will occur, try to run this and you will get to know.
I think you have wrote in other class x =60 and not i1.x ,former (x=60) will not give u any error but later (i1.x) will definetly give. That is what the 10th point is all about.
Hope u got it :)
Shifar Shifz says
Nice and simple article. but I’ve a doubt. You said “Methods with same signature but different return type can’t be implemented at a time for two or more interfaces.”. but I can do that without any compilation error.
Akshay says
As you mentioned
We can’t instantiate an interface in java.
But In first example :
MyInterface obj = new XYZ();
obj. method1();
Please correct if I am wrong
Vetrivel says
MyInterface obj = new XYZ();
obj. method1();
Here the class XYZ is instantiated not the interface.
Please do correct if i m wrong.
sanjay says
This is not the object of interface but here object of XYZ class is created —- new XYZ().
and giving the object reference of XYZ class to interface Myinterface.
so finally
MyInterface obj = new XYZ();
obj. method1();
Venki says
We can’t create Object for an interface, and abstract classes but we can create an reference variable of the interface and abstract class and we can perform Upcasting i.e,
MyInterface obj; /*here reference variable obj of Interface is created.*/
obj = new XYZ(); /*here Object of XYZ class is created and reference is stored in reference variable obj of Interface.*/ I hope u understand..
Ram says
The point No. 9 is wrong.
/*
9) Interface variables must be initialized at the time of declaration otherwise compiler will through an error.
*/
this code is working:
interface a
{
int x;
}
class my implements a
{
}
class JAP{
public static void main(String ar[])
{
my obj=new my();
System.out.println(“The value of x is :”+obj.x);
}
}
//The output is:
//The value of x is :0
Chaitanya Singh says
Dude, Your code is throwing compilation error: Exception in thread “main” java.lang.Error: Unresolved compilation problem: The blank final field x may not have been initialized. Since interface variables are by default final, they must be initialized at the time of declaration.
Maruthi says
In an interface we can create class or only abstract methods only…..
karim mirazul says
well done !!! Keep it up….
good work
Raviteja says
Can u explain about Upcasting and Downcasting in interface and sub interface.can u please help me.
yogita says
this is very helpful for us .. ty
Devarati Tripathi says
Your Java tutorials are wonderful. So much so that did not even have to thing about surfing through youtube. :p
meera says
Multiple Inheritance done by Interface… except any other main advantages in interface than abstract??
Naresh Kumar Davuluri says
Hi Team,
I think Concrete methods also can exist inside an interface when they are declared as “Static”. Could you please explain why and include the same in the tutorial.
Thanks,
Naresh.
Shubham Tayal says
Really, this site is awesome.
content of this site is very useful to understand a particular topic.
sherry says
I just feel confuse, why we need interface? it looks like a framework, all the method we should implement again? then why we need the interface? we can implement the method in our class with out the interface!
Preena says
@Sherry – Thats the whole point, providing a framework! While inherited classes implement those methods for interface, we follow the rule of having same method signature.
For e.g., Imagine there are 3 members coding 3 different classes for the same project say for e.g., interface Shape, classes – Circle, Rect, Triangle, each of these classes should calculate area and the formulas are diff (impl different) for each class, one may give getArea(), other fetchArea(), may be retrieveArea() as well, but if we define this in interface, all 3 would be bound to use common method signature say, would stick to getArea(). This improves readability, provides some standardization. Same scenario just imagine with say 30 classes or so…
sadik says
Hi Preena,
Very thanks for the info. Is there any other advantage besides that ?
tarang sachdev says
it is a super explanation about interface .
avanica says
Hi,
Can u please exaplain how the interface provide security ?
Oshin Bakshi says
Really, appreciated. What a way to explain the topic , the best thing is in one page everything has been covered and I got my concepts more cleared.
Archana Chauhan says
(default methods are not supported in -source 1.8) This error occurs in Java when i compile default method in interface. Can someone help me?
sateesh says
I got confused about this plz help,
Using interface write a program on polymorphism.
vishnu says
hii i have confusion about nested interface, why are using ‘.’ and why are not accessing outer interface method.
Song says
Since java 8, interface can have default and static methods. If that means interface does not provide full abstraction any more. And also, the class that implements interface must implement all the abstract methods of that interface, not all the methods.
Chaitanya Singh says
Yes you are right, I have already covered that here: Java 8 interface changes