Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use an interface in java? [closed]

Tags:

java

interface

A good example of when exactly to use interfaces specifically in Java would be ideal and any specific rulings that apply.

like image 893
Julio Avatar asked Apr 06 '10 16:04

Julio


People also ask

When would you use an interface in Java?

In Java, an interface specifies the behavior of a class by providing an abstract type. As one of Java's core concepts, abstraction, polymorphism, and multiple inheritance are supported through this technology. Interfaces are used in Java to achieve abstraction.

Should you always use an interface Java?

No, every class should not have an interface. It's overkill squared. You use an interface when you need to abstract what's done from how it's done, and you're certain that the implementation can change.

When should programmers use an interface as opposed to inheritance?

Interfaces are appropriate when you are really defining a contract between two objects that is invariant over time. Abstract base types are better for defining a common base for a family of types.

When should an interface be used?

You should use an interface if you want a contract on some behavior or functionality. You should not use an interface if you need to write the same code for the interface methods. In this case, you should use an abstract class, define the method once, and reuse it as needed.


1 Answers

A good place to look at would be the collections framework.

java.util.List //interface  java.util.ArrayList //Concrete class java.util.LinkedList //Concrete class 

So you can write code like this:

List l = new ArrayList();  l.add(..) //do something else. 

If in future you want to change the implementation with say LinkedList or you own AwesomeList which implements List interface, all you have to do is change the very first line to:

List l = new MyAwesomeList(); or List l = new LinkedList(); 

The rest of the code would follow through.

like image 160
coolest_head Avatar answered Oct 19 '22 01:10

coolest_head