Why Do We Need Interfaces in Java

Why need interfaces in java?

Your question is about the difference between abstract methods and interfaces. But I think you are forgetting one thing that all the methods in an interface are abstract. So the methods in an interface and an abstract are same.

Well, the need for an interface is to fulfill the need of multiple inheritance.
Abstract classes are used when you need to create a concrete class, but want to make sure that there is some common state in all the subclasses or a possible common implementation for some operations.

When should I use an interface in java?

Use interfaces to define an application programming contract (blueprint, interface) which "3rd-party" vendors have to fully adhere and implement. This way the endusers can just code against the API contract and easily switch of the concrete implementation "under the hoods" without changing the code.

The JDBC API is an excellent example. It exist of almost only interfaces. The concrete implementations are provided as "JDBC drivers". This enables you to write all the JDBC code independent of the database (DB) vendor. You can just change the JDBC driver without changing any line of Java code (except of any hardcoded DB-specific SQL code) whenever you'd like to switch of DB vendor.

Another example is the Java EE API, it also contains pretty much interfaces and abstract classes. The concrete implementations are provided as "Java EE application servers", "Servletcontainers", etc, such as Sun Glassfish, Apache Tomcat, etc. This enables you to deploy the webapplication (WAR) to whatever Java web server you like.

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.

}

}

Why interface really needed when normal class can do the same work

No doubt your code works even without the interface at this moment, but. Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

For example, if you have multiple animal classes, each implementing Animal, if later on you want to change the structure of the Animal interface, it helps you to easier change the structure of all your animal calsses.

Another example, lets say you work on a group object, and the leader tells you and someone else to make some classes based on a structure given by him (the interface), implementing the interface asures that you got all the method names and structures right. If later on the leader decides that the structure of the classes isn't good, he will change the interface, forcing you to change your class.

For more information, read What is an interface or Undersanding interfaces and their Usefullness

Why do we need interface while we can do the same with class itself?

An interface is a contract (or a protocol, or a skeleton or a common understanding) of what the classes can do.

When a class implements a certain interface, it promises to provide implementation to all the abstract methods declared in the interface.

Interface defines a set of common behaviors. The classes implement the interface agrees to these behaviors and provide their own implementation to the behaviors. This allows you to program at the interface, instead of the actual implementation.

In short:
A class is just an implementation of that contract nothing else

Why should we use interface if we can simply override methods of the superclass or use abstract classes?

To explain why interfaces are used, you have to first understand a problem with inheritance. It's called the Diamond Problem. Simply, if a class, D inherits from two classes B and C, and B and C both inherit from the same class A, which implementation of the methods from A does D get?

Sample Image

What we're left with is a method ambiguity that Java does not like! So the way of preventing this is to make sure that D can only ever have one superclass, so it could inherit from either A, B or C, but never more than one. So that prevents the problem, but we lose all of the perks that multiple inheritance offers!

Enter the Interface. This allows us to have the perks of multiple inheritance (referencing the single class as various different types) and still avoid the diamond problem, because the implementing class provides the method. This removes the method ambiguity.

This means that, for example:

public abstract class MyClass {
public void doSomething();
}

public class MyConcreteClass extends MyClass {
public void doSomething() {
// do something
}
}

You can either refer to an instance of MyConcreteClass as

 MyClass class = new MyConcreteClass();

or

 MyConcreteClass class = new MyConcreteClass();

But never anything else, given this implementation. You can't extend more classes because you'll potentially get the diamond problem, but you CAN include an Interface

public class MyConcreteClass extends MyClass implements Serializable {
}

All of a sudden, you can say..

Seralizable myClass = new MyConcreteClass();

Because myClass is a Serializable. This is excellent for decoupling classes from one another, when a method might not need to know that it is an instance of MyConcreteClass, only that it has a necessary subset of methods.

In short: You can implement many interfaces, but you can only inherit one class.

Do interfaces have any purpose besides achieving polymorphism and multiple inheritance?

if an interface were inherited by only one class, it would be useless

I agree, but you can read a lot of discussion on this topic in Java Interfaces Methodology: Should every class implement an interface?

when an interface is inherited by multiple classes, it makes no difference unless it is used for polymorphism

I agree, it would be silly to implement an interface and then bypass it by invoking its methods directly on the concrete class. The purpose of implementing an interface is to have its abstract methods called, which is polymorphism in action. Since polymorphism is the primary tool of Object Oriented Programming, you could take this statement a step further and say that OOP makes no difference unless it is used for polymorphism.

the only thing that makes implementation different from extension is multiple inheritances

No, the primary difference between these Java constructs is that interface implementation facilitates stateless inheritance whereas class extension facilitates stateful inheritance. Java happens to support multiple stateless inheritance and single stateful inheritance. This dichotomy may be considered a mistake.

Do interfaces have any purpose besides achieving polymorphism and multiple inheritance?

In practice, yes. You can find interfaces used for other purposes such as constant interfaces or marker interfaces. Whether these practices are advisable has been debated.

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



Related Topics



Leave a reply



Submit