Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Interfaces Methodology: Should every class implement an interface?

Tags:

I've been programming in Java for a few courses in the University and I have the following question:

Is it methodologically accepted that every class should implement an interface? Is it considered bad practice not to do so? Can you describe a situation where it's not a good idea to use interfaces?

Edit: Personally, I like the notion of using Interfaces for everything as a methodology and habit, even if it's not clearly beneficial. Eclipse automatically created a class file with all the methods, so it doesn't waste any time anyway.

like image 700
Amir Rachum Avatar asked Apr 17 '10 17:04

Amir Rachum


People also ask

Does every Java class implement an interface?

Every class does implement an interface (i.e. contract) insofar as it provides a non-private API. Whether you should choose to represent the interface separately as a Java interface depends on whether the implementation is "a concept that varies".

Should every class implement an interface?

When discussing these principles in the book, I regularly encourage the reader to add more interfaces to their classes, to make the overall design of the package or application more flexible. However, not every class needs an interface, and not every interface makes sense.

When a class implements an interface it need to --- all the interface methods?

That means all the methods in an interface are declared with an empty body and are public and all fields are public, static, and final by default. A class that implements an interface must implement all the methods declared in the interface.

Do all Java classes need to implement multiple interfaces?

A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class.


1 Answers

You don't need to create an interface if you are not going to use it.

Typically you need an interface when:

  • Your program will provide several implementations for your component. For example, a default implementation which is part of your code, and a mock implementation which is used in a JUnit test. Some tools automate creating a mock implementation, like for instance EasyMock.
  • You want to use dependency injection for this class, with a framework such as Spring or the JBoss Micro-Container. In this case it is a good idea to specify the dependencies from one class with other classes using an interface.
like image 195
Philippe Grenet Avatar answered Oct 26 '22 03:10

Philippe Grenet