What Is an Interface in Java

What is an interface in Java?

An interface is a special form of an abstract class which does not implement any methods. In Java, you create an interface like this:

interface Interface
{
void interfaceMethod();
}

Since the interface can't implement any methods, it's implied that the entire thing, including all the methods, are both public and abstract (abstract in Java terms means "not implemented by this class"). So the interface above is identical to the interface below:

public interface Interface
{
abstract public void interfaceMethod();
}

To use this interface, you simply need to implement the interface. Many classes can implement an interface, and a class can implement many interfaces:

interface InterfaceA
{
void interfaceMethodA();
}

interface InterfaceB
{
void interfaceMethodB();
}

public class ImplementingClassA
implements InterfaceA, InterfaceB
{
public void interfaceMethodA()
{
System.out.println("interfaceA, interfaceMethodA, implementation A");
}

public void interfaceMethodB()
{
System.out.println("interfaceB, interfaceMethodB, implementation A");
}
}

public class ImplementingClassB
implements InterfaceA, InterfaceB
{
public void interfaceMethodA()
{
System.out.println("interfaceA, interfaceMethodA, implementation B");
}

public void interfaceMethodB()
{
System.out.println("interfaceB, interfaceMethodB, implementation B");
}
}

Now if you wanted you could write a method like this:

public void testInterfaces()
{
ImplementingClassA u = new ImplementingClassA();
ImplementingClassB v = new ImplementingClassB();
InterfaceA w = new ImplementingClassA();
InterfaceA x = new ImplementingClassB();
InterfaceB y = new ImplementingClassA();
InterfaceB z = new ImplementingClassB();

u.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation A"
u.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation A"
v.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation B"
v.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation B"
w.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation A"
x.interfaceMethodA();
// prints "interfaceA, interfaceMethodA, implementation B"
y.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation A"
z.interfaceMethodB();
// prints "interfaceB, interfaceMethodB, implementation B"
}

However, you could never do the following:

public void testInterfaces()
{
InterfaceA y = new ImplementingClassA();
InterfaceB z = new ImplementingClassB();

y.interfaceMethodB(); // ERROR!
z.interfaceMethodA(); // ERROR!
}

The reason you can't do this is that y is of type interfaceA, and there is no interfaceMethodB() in interfaceA. Likewise, z is of type interfaceB and there is no interfaceMethodA() in interfaceB.

I mentioned earlier that interfaces are just a special form of an abstract class. To illustrate that point, look at the following code.

interface Interface
{
void abstractMethod();
}

abstract public class AbstractClass
{
abstract public void abstractMethod();
}

You would inherit from these classes almost exactly the same way:

public class InheritsFromInterface
implements Interface
{
public void abstractMethod() { System.out.println("abstractMethod()"); }
}

public class InteritsFromAbstractClass
extends AbstractClass
{
public void abstractMethod() { System.out.println("abstractMethod()"); }
}

In fact, you could even change the interface and the abstract class like this:

interface Interface
{
void abstractMethod();
}

abstract public class AbstractClass
implements Interface
{
abstract public void abstractMethod();
}

public class InheritsFromInterfaceAndAbstractClass
extends AbstractClass implements Interface
{
public void abstractMethod() { System.out.println("abstractMethod()"); }
}

However, there are two differences between interfaces and abstract classes.

The first difference is that interfaces cannot implement methods.

interface Interface
{
public void implementedMethod()
{
System.out.println("implementedMethod()");
}
}

The interface above generates a compiler error because it has an implementation for implementedMethod(). If you wanted to implement the method but not be able to instantiate the class, you would have to do it like this:

abstract public class AbstractClass
{
public void implementedMethod()
{
System.out.println("implementedMethod()");
}
}

That's not much of an abstract class because none of its members are abstract, but it is legal Java.

The other difference between interfaces and abstract classes is that a class can inherit from multiple interfaces, but can only inherit from one abstract class.

abstract public class AbstractClassA { }
abstract public class AbstractClassB { }
public class InheritsFromTwoAbstractClasses
extends AbstractClassA, AbstractClassB
{ }

The code above generates a compiler error, not because the classes are all empty, but because InheritsFromTwoAbstractClasses is trying to inherit from two abstract classes, which is illegal. The following is perfectly legal.

interface InterfaceA { }
interface InterfaceB { }
public class InheritsFromTwoInterfaces
implements InterfaceA, InterfaceB
{ }

The first difference between interfaces and abstract classes is the reason for the second difference. Take a look at the following code.

interface InterfaceA
{
void method();
}

interface InterfaceB
{
void method();
}

public class InheritsFromTwoInterfaces
implements InterfaceA, InterfaceB
{
void method() { System.out.println("method()"); }
}

There's no problem with the code above because InterfaceA and InterfaceB don't have anything to hide. It's easy to tell that a call to method will print "method()".

Now look at the following code:

abstract public class AbstractClassA
{
void method() { System.out.println("Hello"); }
}

abstract public class AbstractClassB
{
void method() { System.out.println("Goodbye"); }
}

public class InheritsFromTwoAbstractClasses
extends AbstractClassA, AbstractClassB
{ }

This is exactly the same as our other example, except that because we're allowed to implement methods in abstract classes, we did, and because we don't have to implement already-implemented methods in an inheriting class, we didn't. But you may have noticed, there's a problem. What happens when we call new InheritsFromTwoAbstractClasses().method()? Does it print "Hello" or "Goodbye"? You probably don't know, and neither does the Java compiler. Another language, C++ allowed this kind of inheritance and they resolved these issues in ways that were often very complicated. To avoid this kind of trouble, Java decided to make this "multiple inheritance" illegal.

The downside to Java's solution that the following can't be done:

abstract public class AbstractClassA
{
void hi() { System.out.println("Hello"); }
}

abstract public class AbstractClassB
{
void bye() { System.out.println("Goodbye"); }
}

public class InheritsFromTwoAbstractClasses
extends AbstractClassA, AbstractClassB
{ }

AbstractClassA and AbstractClassB are "mixins" or classes that aren't intended to be instantiated but add functionality to the classes that they are "mixed into" through inheritance. There's obviously no problem figuring out what happens if you call new InheritsFromTwoAbstractClasses().hi() or new InheritsFromTwoAbstractClasses().bye(), but you can't do that because Java doesn't allow it.

(I know this is a long post, so if there are any mistakes in it please let me know and I will correct them.)

Interfaces in Java - what are they for?

An interface allows you to provide a different implementation at runtime, inject dependencies, separate concerns, use different implementations for testing.

Just think of an interface as a contract that a class guarantees to implement. The concrete class that implements the interface is irrelevant. Don't know if this helps.

Figured some code might help. This doesn't explain everything there is more to interfaces, keep reading but I hope this gets you started. Point here is that you can vary the implementation...

package stack.overflow.example;

public interface IExampleService {
void callExpensiveService();
}

public class TestService implements IExampleService {

@Override
public void callExpensiveService() {
// This is a mock service, we run this as many
// times as we like for free to test our software

}
}

public class ExpensiveService implements IExampleService {
@Override
public void callExpensiveService() {
// This performs some really expensive service,
// Ideally this will only happen in the field
// We'd rather test as much of our software for
// free if possible.
}
}

public class Main {

/**
* @param args
*/
public static void main(String[] args) {

// In a test program I might write
IExampleService testService = new TestService();
testService.callExpensiveService();

// Alternatively, in a real program I might write
IExampleService testService = new ExpensiveService();
testService.callExpensiveService();

// The difference above, is that we can vary the concrete
// class which is instantiated. In reality we can use a
// service locator, or use dependency injection to determine
// at runtime which class to implement.

// So in the above example my testing can be done for free, but
// real world users would still be charged. Point is that the interface
// provides a contract that we know will always be fulfilled, regardless
// of the implementation.

}

}

what is the actual use of interface in java?

What you like : thousands of abstract methods in one Abstract Class and inherit this class OR make as many interfaces for specific abstract methods and use those only you want by inheriting as many interfaces as needed...

abstract class A
{
//thousands of abstract method();
abstract methodA();
abstract methodB();
abstract methodC();
}

//OR
interface ForOnlymethodA
{
void methodA();
}
interface FormethodBandmethodC
{
void methodB();
void methodC();
}

So, use that method only what you just need by inheriting particular interface, if you are inheriting Abstract classes then you are unnecessarily inheriting all methods that you don't need in one class and may be needed in some other classes..

How are Java interfaces used?

Interface in java is like a contract with the implementing class. When you implement an interface you have to make sure that either you implement all the methods in the interface or make your class abstract. Lets take a real like analogy.

You are creating a Car. Now as you know there can be a number of cars out there i.e. Mercedes, BMW, Audi and so on. You want to make sure that each Car should contain changeGear(), hasWheels(), hasDoors() methods in them, so how would you force this criteria on all possible cars. Simply create an interface named Car that has all these methods in it like

public interface Car{
boolean changeGear();
boolean hasWheels();
boolean hasDoors();
}

Now every class that implements this interface has to implement all these methods. So, in future if you create a Ferrari class implementing Car interface it has to abide by this contract.

Edit: A thing to note here is that all the classes that implement the interface are not restricted to use only the methods from the interface. It is just like the implementing class has to make sure that it at least implements the methods from interface. Like in our example Ferrari class can very well implement the isSportCar() method which is only contained in Ferrari class.

What's the difference between interface and @interface in java?

The @ symbol denotes an annotation type definition.

That means it is not really an interface, but rather a new annotation type -- to be used as a function modifier, such as @override.

See this javadocs entry on the subject.

What does an interface in Java interface with?

Software interfaces are one-way (though there are ways to pass the calling object as a reference to the callee), unlike Electrical connectors that interface both ways directly.

If you accept that difference in definition then the object 'implementing' the interface, is the object to be interfaced with. it allows other objects to connect to it using a well defined set of methods.

To compare it further to electronics, if 3 different types of devices all support audio-jacks, then all 3 devices essentially state: you can listen to me, I play audio. They could be very different devices (mp3 player, sonar, geiger counter) but they all clearly state: if you plug in a headphone, you can get sound out of me.

This is what an interface does in software. it states: I provide feature X, no matter what actual component I am.

so anything that implements the Map interface, can have .get(...) and .values() and .keySet() called on it. Anything that implements an AudioStream interface will yield an audiostream when called.

The object interfacing with the object supplying the interface can interact with this object in a predefined and well documented way. Ofcourse, how the object providing the interface actually makes it work can be completely different.

How does an Interface in Java work?

An interface exists to facilitate polymorphism. It allows declaring a contract that any class that implements the interface must honor. And so it is a way to achieve abstraction and model complexity by looking for commonality between things.

An example? How about shapes? All shapes have an area, right? So you could have the following classes:

  • Square
  • Circle

Then let's say you have another class that allows you to collect shapes, and return the total area:

for (Shape shape in shapes)
{
area += shape.area() //This is polymorphism
}

In the example above, we don't care whether the shape is a square or a circle. We can accept either. We only care that it implements the Shape interface. Each object will provide their own custom implementation of area - these internal details aren't important, only that it honors the area contract . See now how we're managing complexity? We can use the class without having to worry about all of the things that go on inside. At this point what it does is important to us, not how it does it, which lets us focus on the problem at hand not getting distracted by complex details.

This polymorphism is one of the reasons why object oriented programming was considered such a powerful evolutionary step in programming. The other key foundation concepts in Object Oriented Programming are:

  • Encapsulation
  • Inheritance

. . . you'll also need to learn these.

Abstract Base Class vs Interface

As a comment said, another way to achieve polymorphism is to use an Abstract Base Class. Which should you choose?

  • Use an interface class implementing it will have its own hierarchy and dependencies. For example a media player. A Movie Player and a Sound Player might have totally different base classes, so use an interface.

  • Use an Abstract base class when you have some commonality between things, but the specifics vary. For example a message parsing framework.

Is an interface a class?

An interface isn't a class, but you could say that both interfaces and classes are types.

From the Java specification:

In the Java programming language, every variable and every expression has a type that can be determined at compile-time. The type may be a primitive type or a reference type. Reference types include class types and interface types.

Notice though there is a special class called Class<T> that can represent both classes and interfaces:

Instances of the class Class represent classes and interfaces in a running Java application.

The fact that an interface is represented by a Class instance where isInterface is true could give you the impression that an interface is just a special type of class. However this is not the case.

What is the purpose of the default keyword in Java?

It's a new feature in Java 8 which allows an interface to provide an implementation. Described in Java 8 JLS-13.5.6. Interface Method Declarations which reads (in part)

Adding a default method, or changing a method from abstract to default, does not break compatibility with pre-existing binaries, but may cause an IncompatibleClassChangeError if a pre-existing binary attempts to invoke the method. This error occurs if the qualifying type, T, is a subtype of two interfaces, I and J, where both I and J declare a default method with the same signature and result, and neither I nor J is a subinterface of the other.

What's New in JDK 8 says (in part)

Default methods enable new functionality to be added to the interfaces of libraries and ensure binary compatibility with code written for older versions of those interfaces.



Related Topics



Leave a reply



Submit