Interface in Java

Q. What is an interface?

Interface looks like 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). Also, the variables declared in an interface are public, static & final by default.

Example of Interface
interface Moveable
        {
             int AVERAGE-SPEED=40;
             void move();
         }

Interface-1

NOTE* : Compiler automatically converts methods of Interface as public and abstract, and the data members as public, static and final by default.

Q. Why use Java interface?

There are mainly three reasons to use interface. They are given below.
1. Without bothering about the implementation part, we can achieve the security of implementation
2. In java, multiple inheritance is not allowed, However by using interfaces you can achieve the same. A class can extend only one class but can implement any number of interfaces. It saves you from Deadly Diamond of Death(DDD) problem.

Understanding relationship between classes and interfaces:-

As shown in the figure given below, a class extends another class, an interface extends another interface but a class implements an interface.

Interface-2

# Here are the key points to remember about interfaces:

1) We can’t instantiate an interface in java.
2) Interface provides complete abstraction as none of its methods can 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 implementing any interface must implement all the methods, otherwise the class should be declared as “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.
9) Interface variables must be initialized at the time of declaration otherwise compiler will through 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) Any 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 e.g:
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
       System.out.println(x);
       System.out.println(A.x);
       System.out.println(B.x);
     }
}

# Difference between Abstract class Vs Interface:-

Abstract class

Interface

Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods. Since Java 8, it can have default and static methods also.
Abstract class doesn’t support multiple inheritance. Interface supports multiple inheritance.
Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables.
Abstract class can provide the implementation of interface. Interface can’t provide the implementation of abstract class.
The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
Example:
public abstract class Shape{
     public abstract void draw();
}
Example:
public interface Drawable{
     void draw();
}

Q) What is marker or tagged interface?

Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface. Example of market interface is Serializable, Clonnable and Remote interface.

Q. Why Marker or Tag interface do in Java?

Looking carefully on marker interface in Java e.g. Serializable, Clonnable and Remote it looks they are used to indicate something to compiler or JVM. So if JVM sees a Class is Serializable it done some special operation on it, similar way if JVM sees one Class is implement Clonnable it performs some operation to support cloning. Same is true for RMI and Remote interface. So in short Marker interface indicate, signal or a command to Compiler or JVM.

(This is pretty standard answer of question about marker interface and once you give this answer most of the time interviewee definitely asked “Why this indication can not be done using a flag inside a class?” this make sense right? Yes this can be done by using a boolean flag or a String but doesn’t marking a class like Serializable or Clonnable makes it more readable and it also allows to take advantage of Polymorphism in Java)

Q. Where Should I use Marker interface in Java?

Apart from using built in marker interface for making a class Serializable or Clonnable. One can also develop his own marker interface. Marker interface is a good way to classify code. You can create marker interface to logically divide your code and if you have your own tool than you can perform some pre-processing operation on those classes. Particularly useful for developing API and framework like Spring or Struts.
After introduction of Annotation on Java5, Annotation is better choice than marker interface and JUnit is a perfect example of using Annotation e.g. @Test for specifying a Test Class. Same can also be achieved by using Test marker interface.

Another use of marker interface in Java

One more use of marker interface in Java can be commenting. a marker interface called Thread Safe can be used to communicate other developers that classes implementing this marker interface gives thread-safe guarantee and any modification should not violate that. Marker interface can also help code coverage or code review tool to find bugs based on specified behavior of marker interfaces.
Again Annotations are better choice @ThreadSafe looks lot better than implementing ThraedSafe marker interface.

In summary marker interface in Java is used to indicate something to compiler, JVM or any other tool but Annotation is better way of doing same thing.


In this section, If you come across any questions or queries, post it to me. I will try to provide solutions to your queries. You can email me at seleniumautomationtesterblog@gmail.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s