WTF is Java Interface ? Explanation, Use and Coded Example.

java interface coded example
java interface coded example

What is Interface ? Why use it? How to make use of it ? How to implement it?

Interface (meaning – interact with)

1- Interface just specify the method declaration (implicitly public and abstract)
Example: public void greetings();

2- We don’t really have to write the “public” keyword as all the methods of
an interface are public by default.
Example: void greetings(); is also correct.

3- Interface can only contain fields which are (implicitly public static final)
Example: public static final String name = “Navjot”;


String name = “Navjot”; is also correct and its (public static and final by default
so, we dont really need to write these).

4- An Interface like an abstract class cannot be instantiated (meaning we cant create
objects of an interface).

5- An Interface do not have a constructor (as we cant create object what do we need
constructor for?).

6- If a class that implements an interface doesn’t implement/define all the methods
of that interface, then that class must be declared as an abstract class and method
declarations must be provided by the subclasses that extent the abstract class.

Below is an example –

How we can create an Interface, using the word “interface” lowerecase and then naming your interface in my case I called it “Interface” (for example only, in real life please use more descriptive names that explain what the interface actually do?

Lets create an “interface”.

Our interface will have 2 variables named – firstName and lastName.

Also, we will create 2 abstract methods named – greetings() and guessAge()

You will see these variables and methods in use once we move to the Interface Use/Implementation part. Which is going to be more fun than defining an interface, in the implementation section, we will actually learn a use-case of interface.

java interface coded example
Java Interface Coded example

Lets, Use/Implement our interface that we just created –

To use a interface, we need to use “implements” keyword (lowercase) and the interface name (in this case “Interface”).

Cool. Now, at-least – We know how to get started with implementing an interface.

Next Step is to make use of it – Look below in the code to see how we implement its abstract methods and then use the class to create an InterfaceImplementation Object.

Java Interface Implementation Example

Running this code in a coding environment like eclipse or netbeans will help you see outputs of the code.

You may also be interested in other Java Articles and Software Development Tutorials, News and Updates

Please leave your lovely comments down below and I will try to reply to every single comment if possible.