Applications of interfaces in java

Interface in java with example programs

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.:

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 interface extends 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(); >>
implementation of method1

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.

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.

Читайте также:  Good coding practice in java

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.

All of the above statements are identical.

9) Interface variables must be initialized at the time of declaration otherwise compiler will throw an 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:

  1. Without bothering about the implementation part, we can achieve the security of implementation
  2. 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.
Читайте также:  Preg match php дата

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

Hi i gone through whole java tutorial and found all the concepts describe pretty good………………………..You have done good job………..keep it……………
Regards:
Chetan

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.

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.

the above content was very useful in understanding some basic concepts about interface in java.thanks a lot….

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.

This is a wonderful article. It gives all the details in short and sweet. Thank you very much. Well done guys.

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.

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.

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!

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?

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 . 🙂

I think point number 10 is incorrect..am able to change the variable in implementation class..Its not showing any errors..Plz reply me

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 🙂

Читайте также:  Подсчет количества строк питон

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.

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

MyInterface obj = new XYZ();
obj. method1(); Here the class XYZ is instantiated not the interface.
Please do correct if i m wrong.

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();

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..

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

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.

Источник

Applications of interfaces in java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

Оцените статью