Generalize a pair of method without lossing static typing checks - java

I am working with a pet project trying to practice (pure?) OO and can not figure out how to factorize a common behavior from a couple of classes.
public Solution improve(Solution initialSolution)
{
stopCondition.setInitialSolution(initialSolution);
Solution nextSolution = initialSolution;
do
{
nextSolution = nextSolutionGenerator.generate(nextSolution);
}
while(!stopCondition.isStopConditionReached());
return nextSolution;
}
As you can see, generate is common to both BinaryNextSolutionGenerator and PermutationNextSolutionGenerator. I know that Solution generate(Solution solution) should be in NextSolutionGenerator, however I do not want to lose the type verification at compile time if I send a PermutationSolution instance into a BinaryNextSolutionGenerator instance.
Looks like I have to use generic programming or my design is fundamentally wrong (or is a common tradeoff?), but I would prefer some experienced opinion before.
BTW, generate only calls doGenerate because I am planning to add some common logging code in there.

Make/refactor Solution and Generator to interfaces.
a "good place" for generics would be to refactor Integer getVariable(int idx) to <V extends java.lang.Number> getVariable(int idx)
another "good generic place" is the (exact) type of Soultion "generator.generate"...
Introduce abstract implementations of that interfaces! And put there as much common code as you can (public Solution<V> generate() {...}), enforce needed methods (<S extends Solution<V>> proteced abstract S doGenerate(S prev);) AbstractGenerator is also the place, where you would put the imporve (and public generate) methods.
Extend these abstract classes and implement the enforced methods (with concrete implementations of the solutions)
same with solution builder: work with abstraction, extension
...
https://github.com/xerx593/soq54317950 explains my points better... also outlined improve() and StopCondition<V extends Number, S extends Solution>.

Related

Is it common to declare variables of interface type instead of implement it? [duplicate]

I have seen this mentioned a few times and I am not clear on what it means. When and why would you do this?
I know what interfaces do, but the fact I am not clear on this makes me think I am missing out on using them correctly.
Is it just so if you were to do:
IInterface classRef = new ObjectWhatever()
You could use any class that implements IInterface? When would you need to do that? The only thing I can think of is if you have a method and you are unsure of what object will be passed except for it implementing IInterface. I cannot think how often you would need to do that.
Also, how could you write a method that takes in an object that implements an interface? Is that possible?
There are some wonderful answers on here to this questions that get into all sorts of great detail about interfaces and loosely coupling code, inversion of control and so on. There are some fairly heady discussions, so I'd like to take the opportunity to break things down a bit for understanding why an interface is useful.
When I first started getting exposed to interfaces, I too was confused about their relevance. I didn't understand why you needed them. If we're using a language like Java or C#, we already have inheritance and I viewed interfaces as a weaker form of inheritance and thought, "why bother?" In a sense I was right, you can think of interfaces as sort of a weak form of inheritance, but beyond that I finally understood their use as a language construct by thinking of them as a means of classifying common traits or behaviors that were exhibited by potentially many non-related classes of objects.
For example -- say you have a SIM game and have the following classes:
class HouseFly inherits Insect {
void FlyAroundYourHead(){}
void LandOnThings(){}
}
class Telemarketer inherits Person {
void CallDuringDinner(){}
void ContinueTalkingWhenYouSayNo(){}
}
Clearly, these two objects have nothing in common in terms of direct inheritance. But, you could say they are both annoying.
Let's say our game needs to have some sort of random thing that annoys the game player when they eat dinner. This could be a HouseFly or a Telemarketer or both -- but how do you allow for both with a single function? And how do you ask each different type of object to "do their annoying thing" in the same way?
The key to realize is that both a Telemarketer and HouseFly share a common loosely interpreted behavior even though they are nothing alike in terms of modeling them. So, let's make an interface that both can implement:
interface IPest {
void BeAnnoying();
}
class HouseFly inherits Insect implements IPest {
void FlyAroundYourHead(){}
void LandOnThings(){}
void BeAnnoying() {
FlyAroundYourHead();
LandOnThings();
}
}
class Telemarketer inherits Person implements IPest {
void CallDuringDinner(){}
void ContinueTalkingWhenYouSayNo(){}
void BeAnnoying() {
CallDuringDinner();
ContinueTalkingWhenYouSayNo();
}
}
We now have two classes that can each be annoying in their own way. And they do not need to derive from the same base class and share common inherent characteristics -- they simply need to satisfy the contract of IPest -- that contract is simple. You just have to BeAnnoying. In this regard, we can model the following:
class DiningRoom {
DiningRoom(Person[] diningPeople, IPest[] pests) { ... }
void ServeDinner() {
when diningPeople are eating,
foreach pest in pests
pest.BeAnnoying();
}
}
Here we have a dining room that accepts a number of diners and a number of pests -- note the use of the interface. This means that in our little world, a member of the pests array could actually be a Telemarketer object or a HouseFly object.
The ServeDinner method is called when dinner is served and our people in the dining room are supposed to eat. In our little game, that's when our pests do their work -- each pest is instructed to be annoying by way of the IPest interface. In this way, we can easily have both Telemarketers and HouseFlys be annoying in each of their own ways -- we care only that we have something in the DiningRoom object that is a pest, we don't really care what it is and they could have nothing in common with other.
This very contrived pseudo-code example (that dragged on a lot longer than I anticipated) is simply meant to illustrate the kind of thing that finally turned the light on for me in terms of when we might use an interface. I apologize in advance for the silliness of the example, but hope that it helps in your understanding. And, to be sure, the other posted answers you've received here really cover the gamut of the use of interfaces today in design patterns and development methodologies.
The specific example I used to give to students is that they should write
List myList = new ArrayList(); // programming to the List interface
instead of
ArrayList myList = new ArrayList(); // this is bad
These look exactly the same in a short program, but if you go on to use myList 100 times in your program you can start to see a difference. The first declaration ensures that you only call methods on myList that are defined by the List interface (so no ArrayList specific methods). If you've programmed to the interface this way, later on you can decide that you really need
List myList = new TreeList();
and you only have to change your code in that one spot. You already know that the rest of your code doesn't do anything that will be broken by changing the implementation because you programmed to the interface.
The benefits are even more obvious (I think) when you're talking about method parameters and return values. Take this for example:
public ArrayList doSomething(HashMap map);
That method declaration ties you to two concrete implementations (ArrayList and HashMap). As soon as that method is called from other code, any changes to those types probably mean you're going to have to change the calling code as well. It would be better to program to the interfaces.
public List doSomething(Map map);
Now it doesn't matter what kind of List you return, or what kind of Map is passed in as a parameter. Changes that you make inside the doSomething method won't force you to change the calling code.
Programming to an interface is saying, "I need this functionality and I don't care where it comes from."
Consider (in Java), the List interface versus the ArrayList and LinkedList concrete classes. If all I care about is that I have a data structure containing multiple data items that I should access via iteration, I'd pick a List (and that's 99% of the time). If I know that I need constant-time insert/delete from either end of the list, I might pick the LinkedList concrete implementation (or more likely, use the Queue interface). If I know I need random access by index, I'd pick the ArrayList concrete class.
Programming to an interface has absolutely nothing to do with abstract interfaces like we see in Java or .NET. It isn't even an OOP concept.
What it means is don't go messing around with the internals of an object or data structure. Use the Abstract Program Interface, or API, to interact with your data. In Java or C# that means using public properties and methods instead of raw field access. For C that means using functions instead of raw pointers.
EDIT: And with databases it means using views and stored procedures instead of direct table access.
Using interfaces is a key factor in making your code easily testable in addition to removing unnecessary couplings between your classes. By creating an interface that defines the operations on your class, you allow classes that want to use that functionality the ability to use it without depending on your implementing class directly. If later on you decide to change and use a different implementation, you need only change the part of the code where the implementation is instantiated. The rest of the code need not change because it depends on the interface, not the implementing class.
This is very useful in creating unit tests. In the class under test you have it depend on the interface and inject an instance of the interface into the class (or a factory that allows it to build instances of the interface as needed) via the constructor or a property settor. The class uses the provided (or created) interface in its methods. When you go to write your tests, you can mock or fake the interface and provide an interface that responds with data configured in your unit test. You can do this because your class under test deals only with the interface, not your concrete implementation. Any class implementing the interface, including your mock or fake class, will do.
EDIT: Below is a link to an article where Erich Gamma discusses his quote, "Program to an interface, not an implementation."
http://www.artima.com/lejava/articles/designprinciples.html
You should look into Inversion of Control:
Martin Fowler: Inversion of Control Containers and the Dependency Injection pattern
Wikipedia: Inversion of Control
In such a scenario, you wouldn't write this:
IInterface classRef = new ObjectWhatever();
You would write something like this:
IInterface classRef = container.Resolve<IInterface>();
This would go into a rule-based setup in the container object, and construct the actual object for you, which could be ObjectWhatever. The important thing is that you could replace this rule with something that used another type of object altogether, and your code would still work.
If we leave IoC off the table, you can write code that knows that it can talk to an object that does something specific, but not which type of object or how it does it.
This would come in handy when passing parameters.
As for your parenthesized question "Also, how could you write a method that takes in an object that implements an Interface? Is that possible?", in C# you would simply use the interface type for the parameter type, like this:
public void DoSomethingToAnObject(IInterface whatever) { ... }
This plugs right into the "talk to an object that does something specific." The method defined above knows what to expect from the object, that it implements everything in IInterface, but it doesn't care which type of object it is, only that it adheres to the contract, which is what an interface is.
For instance, you're probably familiar with calculators and have probably used quite a few in your days, but most of the time they're all different. You, on the other hand, knows how a standard calculator should work, so you're able to use them all, even if you can't use the specific features that each calculator has that none of the other has.
This is the beauty of interfaces. You can write a piece of code, that knows that it will get objects passed to it that it can expect certain behavior from. It doesn't care one hoot what kind of object it is, only that it supports the behavior needed.
Let me give you a concrete example.
We have a custom-built translation system for windows forms. This system loops through controls on a form and translate text in each. The system knows how to handle basic controls, like the-type-of-control-that-has-a-Text-property, and similar basic stuff, but for anything basic, it falls short.
Now, since controls inherit from pre-defined classes that we have no control over, we could do one of three things:
Build support for our translation system to detect specifically which type of control it is working with, and translate the correct bits (maintenance nightmare)
Build support into base classes (impossible, since all the controls inherit from different pre-defined classes)
Add interface support
So we did nr. 3. All our controls implement ILocalizable, which is an interface that gives us one method, the ability to translate "itself" into a container of translation text/rules. As such, the form doesn't need to know which kind of control it has found, only that it implements the specific interface, and knows that there is a method where it can call to localize the control.
Code to the Interface Not the Implementation has NOTHING to do with Java, nor its Interface construct.
This concept was brought to prominence in the Patterns / Gang of Four books but was most probably around well before that. The concept certainly existed well before Java ever existed.
The Java Interface construct was created to aid in this idea (among other things), and people have become too focused on the construct as the centre of the meaning rather than the original intent. However, it is the reason we have public and private methods and attributes in Java, C++, C#, etc.
It means just interact with an object or system's public interface. Don't worry or even anticipate how it does what it does internally. Don't worry about how it is implemented. In object-oriented code, it is why we have public vs. private methods/attributes. We are intended to use the public methods because the private methods are there only for use internally, within the class. They make up the implementation of the class and can be changed as required without changing the public interface. Assume that regarding functionality, a method on a class will perform the same operation with the same expected result every time you call it with the same parameters. It allows the author to change how the class works, its implementation, without breaking how people interact with it.
And you can program to the interface, not the implementation without ever using an Interface construct. You can program to the interface not the implementation in C++, which does not have an Interface construct. You can integrate two massive enterprise systems much more robustly as long as they interact through public interfaces (contracts) rather than calling methods on objects internal to the systems. The interfaces are expected to always react the same expected way given the same input parameters; if implemented to the interface and not the implementation. The concept works in many places.
Shake the thought that Java Interfaces have anything what-so-ever to do with the concept of 'Program to the Interface, Not the Implementation'. They can help apply the concept, but they are not the concept.
It sounds like you understand how interfaces work but are unsure of when to use them and what advantages they offer. Here are a few examples of when an interface would make sense:
// if I want to add search capabilities to my application and support multiple search
// engines such as Google, Yahoo, Live, etc.
interface ISearchProvider
{
string Search(string keywords);
}
then I could create GoogleSearchProvider, YahooSearchProvider, LiveSearchProvider, etc.
// if I want to support multiple downloads using different protocols
// HTTP, HTTPS, FTP, FTPS, etc.
interface IUrlDownload
{
void Download(string url)
}
// how about an image loader for different kinds of images JPG, GIF, PNG, etc.
interface IImageLoader
{
Bitmap LoadImage(string filename)
}
then create JpegImageLoader, GifImageLoader, PngImageLoader, etc.
Most add-ins and plugin systems work off interfaces.
Another popular use is for the Repository pattern. Say I want to load a list of zip codes from different sources
interface IZipCodeRepository
{
IList<ZipCode> GetZipCodes(string state);
}
then I could create an XMLZipCodeRepository, SQLZipCodeRepository, CSVZipCodeRepository, etc. For my web applications, I often create XML repositories early on so I can get something up and running before the SQL Database is ready. Once the database is ready I write an SQLRepository to replace the XML version. The rest of my code remains unchanged since it runs solely off of interfaces.
Methods can accept interfaces such as:
PrintZipCodes(IZipCodeRepository zipCodeRepository, string state)
{
foreach (ZipCode zipCode in zipCodeRepository.GetZipCodes(state))
{
Console.WriteLine(zipCode.ToString());
}
}
It makes your code a lot more extensible and easier to maintain when you have sets of similar classes. I am a junior programmer, so I am no expert, but I just finished a project that required something similar.
I work on client side software that talks to a server running a medical device. We are developing a new version of this device that has some new components that the customer must configure at times. There are two types of new components, and they are different, but they are also very similar. Basically, I had to create two config forms, two lists classes, two of everything.
I decided that it would be best to create an abstract base class for each control type that would hold almost all of the real logic, and then derived types to take care of the differences between the two components. However, the base classes would not have been able to perform operations on these components if I had to worry about types all of the time (well, they could have, but there would have been an "if" statement or switch in every method).
I defined a simple interface for these components and all of the base classes talk to this interface. Now when I change something, it pretty much 'just works' everywhere and I have no code duplication.
A lot of explanation out there, but to make it even more simpler. Take for instance a List. One can implement a list with as:
An internal array
A linked list
Other implementations
By building to an interface, say a List. You only code as to definition of List or what List means in reality.
You could use any type of implementation internally say an array implementation. But suppose you wish to change the implementation for some reason say a bug or performance. Then you just have to change the declaration List<String> ls = new ArrayList<String>() to List<String> ls = new LinkedList<String>().
Nowhere else in code, will you have to change anything else; Because everything else was built on the definition of List.
If you program in Java, JDBC is a good example. JDBC defines a set of interfaces but says nothing about the implementation. Your applications can be written against this set of interfaces. In theory, you pick some JDBC driver and your application would just work. If you discover there's a faster or "better" or cheaper JDBC driver or for whatever reason, you can again in theory re-configure your property file, and without having to make any change in your application, your application would still work.
I am a late comer to this question, but I want to mention here that the line "Program to an interface, not an implementation" had some good discussion in the GoF (Gang of Four) Design Patterns book.
It stated, on p. 18:
Program to an interface, not an implementation
Don't declare variables to be instances of particular concrete classes. Instead, commit only to an interface defined by an abstract class. You will find this to be a common theme of the design patterns in this book.
and above that, it began with:
There are two benefits to manipulating objects solely in terms of the interface defined by abstract classes:
Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface that clients expect.
Clients remain unaware of the classes that implement these objects. Clients only know about the abstract class(es) defining the interface.
So in other words, don't write it your classes so that it has a quack() method for ducks, and then a bark() method for dogs, because they are too specific for a particular implementation of a class (or subclass). Instead, write the method using names that are general enough to be used in the base class, such as giveSound() or move(), so that they can be used for ducks, dogs, or even cars, and then the client of your classes can just say .giveSound() rather than thinking about whether to use quack() or bark() or even determine the type before issuing the correct message to be sent to the object.
Programming to Interfaces is awesome, it promotes loose coupling. As #lassevk mentioned, Inversion of Control is a great use of this.
In addition, look into SOLID principals. here is a video series
It goes through a hard coded (strongly coupled example) then looks at interfaces, finally progressing to a IoC/DI tool (NInject)
To add to the existing posts, sometimes coding to interfaces helps on large projects when developers work on separate components simultaneously. All you need is to define interfaces upfront and write code to them while other developers write code to the interface you are implementing.
It can be advantageous to program to interfaces, even when we are not depending on abstractions.
Programming to interfaces forces us to use a contextually appropriate subset of an object. That helps because it:
prevents us from doing contextually inappropriate things, and
lets us safely change the implementation in the future.
For example, consider a Person class that implements the Friend and the Employee interface.
class Person implements AbstractEmployee, AbstractFriend {
}
In the context of the person's birthday, we program to the Friend interface, to prevent treating the person like an Employee.
function party() {
const friend: Friend = new Person("Kathryn");
friend.HaveFun();
}
In the context of the person's work, we program to the Employee interface, to prevent blurring workplace boundaries.
function workplace() {
const employee: Employee = new Person("Kathryn");
employee.DoWork();
}
Great. We have behaved appropriately in different contexts, and our software is working well.
Far into the future, if our business changes to work with dogs, we can change the software fairly easily. First, we create a Dog class that implements both Friend and Employee. Then, we safely change new Person() to new Dog(). Even if both functions have thousands of lines of code, that simple edit will work because we know the following are true:
Function party uses only the Friend subset of Person.
Function workplace uses only the Employee subset of Person.
Class Dog implements both the Friend and Employee interfaces.
On the other hand, if either party or workplace were to have programmed against Person, there would be a risk of both having Person-specific code. Changing from Person to Dog would require us to comb through the code to extirpate any Person-specific code that Dog does not support.
The moral: programming to interfaces helps our code to behave appropriately and to be ready for change. It also prepares our code to depend on abstractions, which brings even more advantages.
If I'm writing a new class Swimmer to add the functionality swim() and need to use an object of class say Dog, and this Dog class implements interface Animal which declares swim().
At the top of the hierarchy (Animal), it's very abstract while at the bottom (Dog) it's very concrete. The way I think about "programming to interfaces" is that, as I write Swimmer class, I want to write my code against the interface that's as far up that hierarchy which in this case is an Animal object. An interface is free from implementation details and thus makes your code loosely-coupled.
The implementation details can be changed with time, however, it would not affect the remaining code since all you are interacting with is with the interface and not the implementation. You don't care what the implementation is like... all you know is that there will be a class that would implement the interface.
It is also good for Unit Testing, you can inject your own classes (that meet the requirements of the interface) into a class that depends on it
Short story: A postman is asked to go home after home and receive the covers contains (letters, documents, cheques, gift cards, application, love letter) with the address written on it to deliver.
Suppose there is no cover and ask the postman to go home after home and receive all the things and deliver to other people, the postman can get confused.
So better wrap it with cover (in our story it is the interface) then he will do his job fine.
Now the postman's job is to receive and deliver the covers only (he wouldn't bothered what is inside in the cover).
Create a type of interface not actual type, but implement it with actual type.
To create to interface means your components get Fit into the rest of code easily
I give you an example.
you have the AirPlane interface as below.
interface Airplane{
parkPlane();
servicePlane();
}
Suppose you have methods in your Controller class of Planes like
parkPlane(Airplane plane)
and
servicePlane(Airplane plane)
implemented in your program. It will not BREAK your code.
I mean, it need not to change as long as it accepts arguments as AirPlane.
Because it will accept any Airplane despite actual type, flyer, highflyr, fighter, etc.
Also, in a collection:
List<Airplane> plane; // Will take all your planes.
The following example will clear your understanding.
You have a fighter plane that implements it, so
public class Fighter implements Airplane {
public void parkPlane(){
// Specific implementations for fighter plane to park
}
public void servicePlane(){
// Specific implementatoins for fighter plane to service.
}
}
The same thing for HighFlyer and other clasess:
public class HighFlyer implements Airplane {
public void parkPlane(){
// Specific implementations for HighFlyer plane to park
}
public void servicePlane(){
// specific implementatoins for HighFlyer plane to service.
}
}
Now think your controller classes using AirPlane several times,
Suppose your Controller class is ControlPlane like below,
public Class ControlPlane{
AirPlane plane;
// so much method with AirPlane reference are used here...
}
Here magic comes as you may make your new AirPlane type instances as many as you want and you are not changing the code of ControlPlane class.
You can add an instance...
JumboJetPlane // implementing AirPlane interface.
AirBus // implementing AirPlane interface.
You may remove instances of previously created types too.
So, just to get this right, the advantage of a interface is that I can separate the calling of a method from any particular class. Instead creating a instance of the interface, where the implementation is given from whichever class I choose that implements that interface. Thus allowing me to have many classes, which have similar but slightly different functionality and in some cases (the cases related to the intention of the interface) not care which object it is.
For example, I could have a movement interface. A method which makes something 'move' and any object (Person, Car, Cat) that implements the movement interface could be passed in and told to move. Without the method every knowing the type of class it is.
Imagine you have a product called 'Zebra' that can be extended by plugins. It finds the plugins by searching for DLLs in some directory. It loads all those DLLs and uses reflection to find any classes that implement IZebraPlugin, and then calls the methods of that interface to communicate with the plugins.
This makes it completely independent of any specific plugin class - it doesn't care what the classes are. It only cares that they fulfill the interface specification.
Interfaces are a way of defining points of extensibility like this. Code that talks to an interface is more loosely coupled - in fact it is not coupled at all to any other specific code. It can inter-operate with plugins written years later by people who have never met the original developer.
You could instead use a base class with virtual functions - all plugins would be derived from the base class. But this is much more limiting because a class can only have one base class, whereas it can implement any number of interfaces.
C++ explanation.
Think of an interface as your classes public methods.
You then could create a template that 'depends' on these public methods in order to carry out it's own function (it makes function calls defined in the classes public interface). Lets say this template is a container, like a Vector class, and the interface it depends on is a search algorithm.
Any algorithm class that defines the functions/interface Vector makes calls to will satisfy the 'contract' (as someone explained in the original reply). The algorithms don't even need to be of the same base class; the only requirement is that the functions/methods that the Vector depends on (interface) is defined in your algorithm.
The point of all of this is that you could supply any different search algorithm/class just as long as it supplied the interface that Vector depends on (bubble search, sequential search, quick search).
You might also want to design other containers (lists, queues) that would harness the same search algorithm as Vector by having them fulfill the interface/contract that your search algorithms depends on.
This saves time (OOP principle 'code reuse') as you are able to write an algorithm once instead of again and again and again specific to every new object you create without over-complicating the issue with an overgrown inheritance tree.
As for 'missing out' on how things operate; big-time (at least in C++), as this is how most of the Standard TEMPLATE Library's framework operates.
Of course when using inheritance and abstract classes the methodology of programming to an interface changes; but the principle is the same, your public functions/methods are your classes interface.
This is a huge topic and one of the the cornerstone principles of Design Patterns.
In Java these concrete classes all implement the CharSequence interface:
CharBuffer, String, StringBuffer, StringBuilder
These concrete classes do not have a common parent class other than Object, so there is nothing that relates them, other than the fact they each have something to do with arrays of characters, representing such, or manipulating such. For instance, the characters of String cannot be changed once a String object is instantiated, whereas the characters of StringBuffer or StringBuilder can be edited.
Yet each one of these classes is capable of suitably implementing the CharSequence interface methods:
char charAt(int index)
int length()
CharSequence subSequence(int start, int end)
String toString()
In some cases, Java class library classes that used to accept String have been revised to now accept the CharSequence interface. So if you have an instance of StringBuilder, instead of extracting a String object (which means instantiating a new object instance), it can instead just pass the StringBuilder itself as it implements the CharSequence interface.
The Appendable interface that some classes implement has much the same kind of benefit for any situation where characters can be appended to an instance of the underlying concrete class object instance. All of these concrete classes implement the Appendable interface:
BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer
Previous answers focus on programming to an abstraction for the sake of extensibility and loose coupling. While these are very important points,
readability is equally important. Readability allows others (and your future self) to understand the code with minimal effort. This is why readability leverages abstractions.
An abstraction is, by definition, simpler than its implementation. An abstraction omits detail in order to convey the essence or purpose of a thing, but nothing more.
Because abstractions are simpler, I can fit a lot more of them in my head at one time, compared to implementations.
As a programmer (in any language) I walk around with a general idea of a List in my head at all times. In particular, a List allows random access, duplicate elements, and maintains order. When I see a declaration like this: List myList = new ArrayList() I think, cool, this is a List that's being used in the (basic) way that I understand; and I don't have to think any more about it.
On the other hand, I do not carry around the specific implementation details of ArrayList in my head. So when I see, ArrayList myList = new ArrayList(). I think, uh-oh, this ArrayList must be used in a way that isn't covered by the List interface. Now I have to track down all the usages of this ArrayList to understand why, because otherwise I won't be able to fully understand this code. It gets even more confusing when I discover that 100% of the usages of this ArrayList do conform to the List interface. Then I'm left wondering... was there some code relying on ArrayList implementation details that got deleted? Was the programmer who instantiated it just incompetent? Is this application locked into that specific implementation in some way at runtime? A way that I don't understand?
I'm now confused and uncertain about this application, and all we're talking about is a simple List. What if this was a complex business object ignoring its interface? Then my knowledge of the business domain is insufficient to understand the purpose of the code.
So even when I need a List strictly within a private method (nothing that would break other applications if it changed, and I could easily find/replace every usage in my IDE) it still benefits readability to program to an abstraction. Because abstractions are simpler than implementation details. You could say that programming to abstractions is one way of adhering to the KISS principle.
An interface is like a contract, where you want your implementation class to implement methods written in the contract (interface). Since Java does not provide multiple inheritance, "programming to interface" is a good way to achieve multiple inheritance.
If you have a class A that is already extending some other class B, but you want that class A to also follow certain guidelines or implement a certain contract, then you can do so by the "programming to interface" strategy.
Q: - ... "Could you use any class that implements an interface?"
A: - Yes.
Q: - ... "When would you need to do that?"
A: - Each time you need a class(es) that implements interface(s).
Note: We couldn't instantiate an interface not implemented by a class - True.
Why?
Because the interface has only method prototypes, not definitions (just functions names, not their logic)
AnIntf anInst = new Aclass();
// we could do this only if Aclass implements AnIntf.
// anInst will have Aclass reference.
Note: Now we could understand what happened if Bclass and Cclass implemented same Dintf.
Dintf bInst = new Bclass();
// now we could call all Dintf functions implemented (defined) in Bclass.
Dintf cInst = new Cclass();
// now we could call all Dintf functions implemented (defined) in Cclass.
What we have: Same interface prototypes (functions names in interface), and call different implementations.
Bibliography:
Prototypes - wikipedia
program to an interface is a term from the GOF book. i would not directly say it has to do with java interface but rather real interfaces. to achieve clean layer separation, you need to create some separation between systems for example: Let's say you had a concrete database you want to use, you would never "program to the database" , instead you would "program to the storage interface". Likewise you would never "program to a Web Service" but rather you would program to a "client interface". this is so you can easily swap things out.
i find these rules help me:
1. we use a java interface when we have multiple types of an object. if i just have single object, i dont see the point. if there are at least two concrete implementations of some idea, then i would use a java interface.
2. if as i stated above, you want to bring decoupling from an external system (storage system) to your own system (local DB) then also use a interface.
notice how there are two ways to consider when to use them.
Coding to an interface is a philosophy, rather than specific language constructs or design patterns - it instructs you what is the correct order of steps to follow in order to create better software systems (e.g. more resilient, more testable, more scalable, more extendible, and other nice traits).
What it actually means is:
===
Before jumping to implementations and coding (the HOW) - think of the WHAT:
What black boxes should make up your system,
What is each box' responsibility,
What are the ways each "client" (that is, one of those other boxes, 3rd party "boxes", or even humans) should communicate with it (the API of each box).
After you figure the above, go ahead and implement those boxes (the HOW).
Thinking first of what a box' is and what its API, leads the developer to distil the box' responsibility, and to mark for himself and future developers the difference between what is its exposed details ("API") and it's hidden details ("implementation details"), which is a very important differentiation to have.
One immediate and easily noticeable gain is the team can then change and improve implementations without affecting the general architecture. It also makes the system MUCH more testable (it goes well with the TDD approach).
===
Beyond the traits I've mentioned above, you also save A LOT OF TIME going this direction.
Micro Services and DDD, when done right, are great examples of "Coding to an interface", however the concept wins in every pattern from monoliths to "serverless", from BE to FE, from OOP to functional, etc....
I strongly recommend this approach for Software Engineering (and I basically believe it makes total sense in other fields as well).
Program to an interface allows to change implementation of contract defined by interface seamlessly. It allows loose coupling between contract and specific implementations.
IInterface classRef = new ObjectWhatever()
You could use any class that implements IInterface? When would you need to do that?
Have a look at this SE question for good example.
Why should the interface for a Java class be preferred?
does using an Interface hit performance?
if so how much?
Yes. It will have slight performance overhead in sub-seconds. But if your application has requirement to change the implementation of interface dynamically, don't worry about performance impact.
how can you avoid it without having to maintain two bits of code?
Don't try to avoid multiple implementations of interface if your application need them. In absence of tight coupling of interface with one specific implementation, you may have to deploy the patch to change one implementation to other implementation.
One good use case: Implementation of Strategy pattern:
Real World Example of the Strategy Pattern
"Program to interface" means don't provide hard code right the way, meaning your code should be extended without breaking the previous functionality. Just extensions, not editing the previous code.
Also I see a lot of good and explanatory answers here, so I want to give my point of view here, including some extra information what I noticed when using this method.
Unit testing
For the last two years, I have written a hobby project and I did not write unit tests for it. After writing about 50K lines I found out it would be really necessary to write unit tests.
I did not use interfaces (or very sparingly) ... and when I made my first unit test, I found out it was complicated. Why?
Because I had to make a lot of class instances, used for input as class variables and/or parameters. So the tests look more like integration tests (having to make a complete 'framework' of classes since all was tied together).
Fear of interfaces
So I decided to use interfaces. My fear was that I had to implement all functionality everywhere (in all used classes) multiple times. In some way this is true, however, by using inheritance it can be reduced a lot.
Combination of interfaces and inheritance
I found out the combination is very good to be used. I give a very simple example.
public interface IPricable
{
int Price { get; }
}
public interface ICar : IPricable
public abstract class Article
{
public int Price { get { return ... } }
}
public class Car : Article, ICar
{
// Price does not need to be defined here
}
This way copying code is not necessary, while still having the benefit of using a car as interface (ICar).

OOP Task (class hierarchy, inheritance, interface, etc.)

Since I am trying to learn more about OOP (Java) I'm working my way through some literature where I found this 'task'. Unfortunately I am having kind of a hard time since I am pretty new to OOP and I don't have any sample solution to this. Maybe some of you can give me some input so can work my way through this.
Define a class hierarchy for these classes:
quadrilateral
convex quadrilateral
trapezoid
parallelogram
rhombus
rectangle
square
Create an instance of each class if possible
Define reasonable attributes and methods in each class
Overload and override methods
Write reasonable constructors for each class
Use modifiers (abstract, static, final, public, protected and private) in a meaningful way
How could an interface be used for this task?
01 Class hierarchy
Okay, this is simple math and you can find tons of information on the hierarchy of quadrilaterals everywhere. Here is what I did:
Creating Objects of each class is no big deal, but I still have some problems with understanding all the OOP-techniques. There are some points where I don't know what would be the better way to do it... (e.g. the square which inherits from two classes, which in java is simply not possible). Also, formulas (like calculating the surface area) would be overwritten all the time anyhow (since they are different most of the time), so why would I need inheritance anyway? Couldn't I just use an interface, use it in all of those classes an force them to implement these formulas?
Greetings - Vulpecula
In real life, you probably would be better off using an interface. Deep inheritance structures like that are often frowned upon; it's generally considered good to 'prefer composition over inheritance' (http://en.wikipedia.org/wiki/Composition_over_inheritance). You might for instance have a 'quadrilateral' interface that defines 'surface area' and 'perimeter', and then have the other shapes satisfy that interface.
If this is a homework question however, then you should probably base the class hierarchy on whatever examples your textbook/teacher have provided previously. It's not about designing robust software, it's about proving to your teacher that you learned how to do things in whatever way they think you should do them.
An abstract class as the base of a moderately complicated hierarchy is not as flexible as an interface. A class--abstract or not--forces a specific type of implementation.
Without thinking too hard about it, here's one way to start:
public interface Quadrilateral {
int getTopMillimeters();
int getLeftMillimeters();
int getRightMillimeters();
int getBottomMillimeters();
}
From this raw data, you could also define
getTopLeftAngle(), getTopRightAngle(), ...
which would all compute their values based on the lengths.
I too would emphasize composition over inheritance. The end-effect can indeed be a complex inheritance structure.
For me, composition is heirarchy of "Composer" classes, which do NOT implement the interface. Such as
public class QuadrilateralComposer {
private final int iTopMM;
private final int iBtmMM;
...
public QuadrilateralComposer(int i_topMM, int i_bottomMM, ...) {
if(i_topMM < 1) {
throw new IllegalArgumentException...
}
if(i_bottomMM < 1) {
throw new IllegalArgumentException...
}
...
iTopMM = i_topMM;
iBtmMM = i_bottomMM;
...
}
public int getTopMillimeters() {
return iTopMM;
}
...
Which is then composed by an abstract class:
public class AbstractQuadrilateral implements Quadrilateral
private final QuadrilateralComposer qc;
public AbstractQuadrilateral(int i_topLen, int i_bottomLen, ...) {
gc = new QuadrilateralComposer(i_topLen, i_bottomLen, ...);
}
public int getTopLength() {
return gc.getTopLength();
}
...
Abstract classes never extend other abstract classes, they only use internal Composers (and actually implement the interface). On the other end, Composers only extend Composers, and use other composers internally.
(Three notes: Protected functions are in the Composer as public function_4prot() and are implemented as protected function(), which call the _4prot version. And sometimes the abstract class can indeed implement everything in the interface. In this case, it would be concrete [non-abstract] and be named "SimpleXYZ", instead of "AbstractXYZ". Finally, static utility functions reside in the Composer.)
If EVERY interface is designed in this way, then ANY class can easily implement ANY interface, regardless which class they must actually extend. If abstract classes extend other abstract classes, that is a lot more work for classes that need to implement the interface, but happen to--and have to--extend something else.
This is not what you asked, but learning this concept changed my code for the WAY better. Seeing it mentioned in the accepted answer made me think through all of it. I've actually been slowly drifting away from inheritance to composition over the past few years, and after reading Effective Java, it was the final nail in the inheritance coffin, as it were.
Okay, the plan now is that I am trying to resolve this without any interface first. So here's the map of inheritance:
I am ignoring the fact, that the square is not only a rectange but also a rhombus.
The abstract class (quadrilateral) will define (but not implement) methods for calculating 'surface area' and 'perimeter'. Overriding methods is easy since every shape has different formumals for calculation but I am not really sure where I could use the overloading feature.
One more thing: Using an interface, would this be the desired way?

Why to use Interfaces, Multiple Inheritance vs Interfaces, Benefits of Interfaces?

I still have some confusion about this thing. What I have found till now is
(Similar questions have already been asked here but I was having some other points.)
Interface is collection of ONLY abstract methods and final fields.
There is no multiple inheritance in Java.
Interfaces can be used to achieve multiple inheritance in Java.
One Strong point of Inheritance is that We can use the code of base class in derived class without writing it again. May be this is the most important thing for inheritance to be there.
Now..
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
Then why to make interfaces ?
NOTE : I have found one case in which interfaces are helpful. One example of it is like in Runnable interface we have public void run() method in which we define functionality of thread and there is built in coding that this method will be run as a separate thread. So we just need to code what to do in thread, Rest is pre-defined. But this thing also can be achieved using abstract classes and all.
Then what are the exact benefits of using interfaces? Is it really Multiple-Inheritance that we achieve using Interfaces?
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
We can't. Interfaces aren't used to achieve multiple inheritance. They replace it with safer, although slightly less powerful construct. Note the keyword implements rather than extends.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
They are not. With interfaces a single class can have several "views", different APIs or capabilities. E.g. A class can be Runnable and Callable at the same time, while both methods are effectively doing the same thing.
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
Interfaces are kind-of multiple inheritance with no problems that the latter introduces (like the Diamond problem).
There are few use-cases for interfaces:
Object effectively has two identities: a Tank is both a Vehicle and a Weapon. You can use an instance of Tank where either the former or the latter is expected (polymorphism). This is rarely a case in real-life and is actually a valid example where multiple inheritance would be better (or traits).
Simple responsibilities: an instance of Tank object in a game is also Runnable to let you execute it in a thread and an ActionListener to respond to mouse events.
Callback interfaces: if object implements given callback interface, it is being notified about its life-cycle or other events.
Marker interfaces: not adding any methods, but easily accessible via instanceof to discover object capabilities or wishes. Serializable and Cloneable are examples of this.
What you are looking for are trait (like in Scala), unfortunately unavailable in Java.
Interfaces are collection of final static fields and abstract methods (Newly Java 8 added support of having static methods in an interface).
Interfaces are made in situations when we know that some task must be done, but how it should be done can vary. In other words we can say we implement interfaces so that our class starts behaving in a particular way.
Let me explain with an example, we all know what animals are. Like Lion is an animal, monkey is an animal, elephant is an animal, cow is an animal and so on. Now we know all animals do eat something and sleep. But the way each animal can eat something or sleep may differ. Like Lion eats by hunting other animals where as cow eats grass. But both eat. So we can have some pseudo code like this,
interface Animal {
public void eat();
public void sleep();
}
class Lion implements Animal {
public void eat() {
// Lion's way to eat
}
public void sleep(){
// Lion's way to sleep
}
}
class Monkey implements Animal {
public void eat() {
// Monkey's way to eat
}
public void sleep() {
// Monkey's way to sleep
}
}
As per the pseudo code mentioned above, anything that is capable of eating or sleeping will be called an animal or we can say it is must for all animals to eat and sleep but the way to eat and sleep depends on the animal.
In case of interfaces we inherit only the behaviour, not the actual code as in case of classes' inheritance.
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
Implementing interfaces is other kind of inheritance. It is not similar to the inheritance of classes as in that inheritance child class gets the real code to reuse from the base class.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
It is said because one class can implement more than one interfaces. But we need to understand that this inheritance is different than classes' inheritance.
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
Implementing an interface puts compulsion on the class that it must override its all abstract methods.
Read more in my book here and here
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
Unfortunately, in colloquial usage, the word inheritance is still frequently used when a class implements an interface, although interface implementation would be a preferable term - IMO, the term inheritance should strictly be used with inheritance of a concrete or abstract class. In languages like C++ and C#, the same syntax (i.e. Subclass : Superclass and Class : Interface) is used for both class inheritance and interface implementation, which may have contributed to the spread of the misuse of the word inheritance with interfaces. Java has different syntax for extending a class as opposed to implementing an interface, which is a good thing.
Q2 If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
You can achieve the 'effect' of multiple inheritance through composition - by implementing multiple interfaces on a class, and then providing implementations for all methods, properties and events required of all the interfaces on the class. One common technique of doing this with concrete classes is by doing 'has-a' (composition) relationships with classes which implement the external interfaces by 'wiring up' the implementation to each of the internal class implementations. (Languages such as C++ do support multiple concrete inheritance directly, but which creates other potential issues like the diamond problem).
Q3 Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
Interfaces allow existing classes (e.g. frameworks) to interact with your new classes without having ever 'seen' them before, because of the ability to communicate through a known interface. Think of an interface as a contract. By implementing this interface on a class, you are contractually bound to meet the obligations required of it, and once this contract is implemented, then your class should be able to be used interchangeably with any other code which consumes the interface.
Real World Example
A 'real world' example would be the legislation and convention (interface) surrounding an electrical wall socket in a particular country. Each electrical appliance plugged into the socket needs to meet the specifications (contract) that the authorities have defined for the socket, e.g. the positioning of the line, neutral and earth wires, the position and colouring of the on / off switch, and the conformance the the electrical voltage, frequency and maximum current that will be supplied through the interface when it is switched on.
The benefit of decoupling the interface (i.e. a standard wall socket) rather than just soldering wires together is that you can plug (and unplug) a fan, a kettle, a double-adapter, or some new appliance to be invented next year into it, even though this appliance didn't exist when the interface was designed. Why? Because it will conform to the requirements of the interface.
Why use interfaces?
Interfaces are great for loose coupling of classes, and are one of the mainstay's of Uncle Bob's SOLID paradigm, especially the Dependency Inversion Principle and Interface Segregation Principles.
Simply put, by ensuring that dependencies between classes are coupled only on interfaces (abstractions), and not on other concrete classes, it allows the dependency to be substituted with any other class implementation which meets the requirements of the interface.
In testing, stubs and mocks of dependencies can be used to unit test each class, and the interaction the class has with the dependency can be 'spyed' upon.
KISS
I have searched for days, nay weeks trying to understand interfaces and seem to read the same generic help; I'm not trying to disparage the contributions, but i think the light-bulb just clicked so I'm chuffed :))
I prefer to Keep It Simple Stupid, so will proffer my new found view of interfaces.
I'm a casual coder but i want to post this code i wrote in VB.NET (the principle is the same for other languages), to help others understand interfaces.
If i have it wrong, then please let others know in follow up comments.
Explanation
Three buttons on a form, clicking each one saves a different class reference to the interface variable (_data). The whole point of different class references into an interface variable, is what i didn't understand as it seemed redundant, then its power becomes evident with the msgbox, i only need to call the SAME method to perform the task i need, in this case 'GetData()', which uses the method in the class that's currently held by the interface reference variable (_data).
So however i wish to get my data (from a database, the web or a text file), it's only ever done using the same method name; the code behind that implementation...i don't care about.
It's then easy to change each class code using the interface without any dependency...this is a key goal in OO and encapsulation.
When to use
Code classes and if you notice the same verb used for methods, like 'GetData()', then it's a good candidate to implement an interface on that class and use that method name as an abstraction / interface.
I sincerely hope this helps a fellow noob with this difficult principle.
Public Class Form1
Private _data As IData = Nothing
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
_data = New DataText()
MsgBox(_data.GetData())
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
_data = New DataDB()
MsgBox(_data.GetData())
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
_data = New DataWeb()
MsgBox(_data.GetData())
End Sub
End Class
Public Interface IData
Function GetData() As String
End Interface
Friend Class DataText : Implements IData
Friend Function GetData() As String Implements IData.GetData
Return "DataText"
End Function
End Class
Friend Class DataDB : Implements IData
Friend Function GetData() As String Implements IData.GetData
Return "DataDB"
End Function
End Class
Friend Class DataWeb : Implements IData
Friend Function GetData() As String Implements IData.GetData
Return "DataWeb"
End Function
End Class
Old question. I'm suprised that nobody quoted the canonical sources: Java: an Overview by James Gosling, Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four or Effective Java by Joshua Bloch (among other sources).
I will start with a quote:
An interface is simply a specification of a set of methods that an object responds to. It does not include any instance variables or implementation. Interfaces can be multiply-inherited (unlike classes) and they can be used in a more flexible way than the usual rigid class
inheritance structure. (Gosling, p.8)
Now, let's take your assumptions and questions one by one (I'll voluntarily ignore the Java 8 features).
Assumptions
Interface is collection of ONLY abstract methods and final fields.
Did you see the keyword abstract in Java interfaces? No. Then you should not consider an interface as a collection of abstract methods. Maybe you are misleaded by the C++ so-called interfaces, which are classes with only pure virtual methods. C++, by design, does not have (and does not need to have) interfaces, because it has mutliple inheritance.
As explained by Gosling, you should rather consider an interface as "a set of methods that an object responds to". I like to see an interface and the associated documentation as a service contract. It describes what you can expect from an object that implements that interface. The documentation should specify the pre and post-conditions (e.g. the parameters should be not null, the output is always positive, ...) and the invariants (a method that does not modify the object internal state). This contract is the heart, I think, of OOP.
There is no multiple inheritance in Java.
Indeed.
JAVA omits many rarely used, poorly understood, confusing features of C++ that in our experience bring more grief than benefit. This primarily consists of operator overloading (although it does have method overloading), multiple inheritance, and extensive automatic coercions. (Gosling, p.2)
Nothing to add.
Interfaces can be used to achieve multiple inheritance in Java.
No, simlpy because there is no multiple inheritance in Java. See above.
One Strong point of Inheritance is that We can use the code of base class in derived class without writing it again. May be this is the most important thing for inheritance to be there.
That's called "implementation inheritance". As you wrote, it's a convenient way to reuse code.
But it has an important counterpart:
parent classes often define at least part of their subclasses' physical representation. Because inheritance exposes a subclass to details of its parent's implementation, it's often said that "inheritance breaks encapsulation" [Sny86]. The implementation of a subclass becomes so bound up with the implementation of its parent class that any change in the parent's implementation will force the subclass to change. (GOF, 1.6)
(There is a similar quote in Bloch, item 16.)
Actually, inheritance serves also another purpose:
Class inheritance combines interface inheritance and implementation inheritance. Interface inheritance defines a new interface in terms of one
or more existing interfaces. Implementation inheritance defines a new implementation in terms of one or more existing implementations. (GOF, Appendix A)
Both use the keyword extends in Java. You may have hierarchies of classes and hierarchies of interfaces. The first ones share implementation, the second ones share obligation.
Questions
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.**
Implementation of an interface is not inheritance. It's implementation. Thus the keyword implements.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?**
No multiple inheritance in Java. See above.
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it./Then why to make interfaces ?/What are the exact benefits of using interfaces? Is it really Multiple-Inheritance that we achieve using Interfaces?
The most important question is: why would you like to have multiple-inheritance? I can think of two answers: 1. to give mutliple types to an object; 2. to reuse code.
Give mutliple types to an object
In OOP, one object may have different types. For instance in Java, an ArrayList<E> has the following types: Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess, AbstractList<E>, AbstractCollection<E> and Object (I hope I have not forgotten anyone). If an object has different types, various consumers will be able use it without be aware of its specificities. I need an Iterable<E> and you give me a ArrayList<E>? It's ok. But if I need now a List<E> and you give me a ArrayList<E>, it's ok too. Etc.
How do you type an object in OOP? You took the Runnable interface as an example, and this example is perfect to illustrate the answer to this question. I quote the official Java doc:
In addition, Runnable provides the means for a class to be active while not subclassing Thread.
Here's the point: Inheritance is a convenient way of typing objects. You want to create a thread? Let's subclass the Thread class. You want an object to have different types, let's use mutliple-inheritance. Argh. It doesn't exist in Java. (In C++, if you want an object to have different types, multiple-inheritance is the way to go.)
How to give mutliple types to an object then? In Java, you can type your object directly. That's what you do when your class implements the Runnable interface. Why use Runnable if your a fan of inheritance? Maybe because your class is already a subclass of another class, let's say A. Now your class has two types: A and Runnable.
With multiple interfaces, you can give multiple types to an object. You just have to create a class that implements multiple interfaces. As long as you are compliant with the contracts, it's ok.
Reuse code
This is a difficult subject; I've already quoted the GOF on breaking the encapsulation. Other answer mentionned the diamond problem. You could also think of the Single Responsibility Principle:
A class should have only one reason to change. (Robert C. Martin, Agile Software Development, Principles, Patterns, and Practices)
Having a parent class may give a class a reason to change, besides its own responsibilities:
The superclass’s implementation may change from release to release, and if it does, the subclass may break, even though its code has not been touched. As a consequence, a subclass must evolve in tandem with its superclass (Bloch, item 16).
I would add a more prosaic issue: I always have a weird feeling when I try to find the source code of a method in a class and I can't find it. Then I remember: it must be defined somewhere in the parent class. Or in the grandparent class. Or maybe even higher. A good IDE is a valuable asset in this case, but it remains, in my mind, something magical. Nothing similar with hierarchies of interfaces, since the javadoc is the only thing I need: one keyboard shortcut in the IDE and I get it.
Inheritance howewer has advantages:
It is safe to use inheritance within a package, where the subclass and the superclass implementations are under the control of the same programmers. It is also safe to use inheritance when extending classes specifically designed and documented for extension (Item 17: Design and document for inheritance or else prohibit it). (Bloch, item 16)
An example of a class "specifically designed and documented for extension" in Java is AbstractList.
But Bloch and GOF insist on this: "Favor composition over inheritance":
Delegation is a way of making composition as powerful for reuse as inheritance [Lie86, JZ91]. In delegation, two objects are involved in handling a request: a receiving object delegates operations to its delegate. This is analogous to subclasses deferring requests to parent classes. (GOF p.32)
If you use composition, you won't have to write the same code again and again. You just create a class that handles the duplications, and you pass an instance of this class to the classes that implements the interface. It's a very simple way to reuse code. And this helps you to follow the Single Responsibility Principle and make the code more testable. Rust and Go don't have inheritance (they don't have classes either), but I don't think that the code is more redundant than in other OOP languages.
Furthermore, if you use composition, you will find yourself naturally using interfaces to give your code the structure and the flexibility it needs (see other answers on use cases of interfaces).
Note: you can share code with Java 8 interfaces
And finally, one last quote:
During the memorable Q&A session, someone asked him [James Gosling]: "If you could do Java over again, what would you change?" "I'd leave out classes" (anywhere on the net, don't know if this is true)
This is very old question and java-8 release have added more features & power to interface.
An interface declaration can contain
method signatures
default methods
static methods
constant definitions.
The only methods that have implementations in interface are default and static methods.
Uses of interface:
To define a contract
To link unrelated classes with has a capabilities (e.g. classes implementing Serializable interface may or may not have any relation between them except implementing that interface
To provide interchangeable implementation e.g. Strategy_pattern
default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces
Organize helper methods in your libraries with static methods ( you can keep static methods specific to an interface in the same interface rather than in a separate class)
Have a look at this related SE question for code example to understanding the concepts better:
How should I have explained the difference between an Interface and an Abstract class?
Coming back to your queries:
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
Interface can contain code for static and default methods. These default methods provides backward compatibility & static methods provides helper/utility functions.
You can't have true multiple inheritance in java and interface is not the way to get it. Interface can contain only constants. So you can't inherit state but you can implement behaviour.
You can replace inheritance with capability. Interface provides multiple capabilities to implementing classes.
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
Refer to "uses of interface" section in my answer.
Inheritance is when one class derives from another class (which can be abstract) or an Interface. The strongest point of object oriented (inheritance) is not reuse of code (there are many ways to do it), but polymorphism.
Polymorphism is when you have code that uses the interface, which it's instance object can be of any class derived from that interface. For example I can have such a method:
public void Pet(IAnimal animal) and this method will get an object which is an instance of Dog or Cat which inherit from IAnimal. or I can have such a code:
IAnimal animal
and then I can call a method of this interface:
animal.Eat() which Dog or Cat can implement in a different way.
The main advantage of interfaces is that you can inherit from some of them, but if you need to inherit from only one you can use an abstract class as well. Here is an article which explains more about the differences between an abstract class and an interface:
http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx
Both Methods Work (Interfaces and Multiple Inheritance).
Quick Practical Short Answer
Interfaces are better when you have several years of experience using Multiple Inheritance that have Super Classes with only method definition, and no code at all.
A complementary question may be: "How and Why to to migrate code from Abstract Classes to Interfaces".
If you are not using many abstract classes, in your application, or you don't have many experience with it, you may prefer to skip interfaces.
Dont rush to use interfaces.
Long Boring Answer
Interfaces are very similar, or even equivalent to abstract Classes.
If your code has many Abstract classes, then its time you start thinking in terms of Interfaces.
The following code with abstract classes:
MyStreamsClasses.java
/* File name : MyStreamsClasses.java */
import java.lang.*;
// Any number of import statements
public abstract class InputStream {
public void ReadObject(Object MyObject);
}
public abstract class OutputStream {
public void WriteObject(Object MyObject);
}
public abstract class InputOutputStream
imnplements InputStream, OutputStream {
public void DoSomethingElse();
}
Can be replaced with:
MyStreamsInterfaces.java
/* File name : MyStreamsInterfaces.java */
import java.lang.*;
// Any number of import statements
public interface InputStream {
public void ReadObject(Object MyObject);
}
public interface OutputStream {
public void WriteObject(Object MyObject);
}
public interface InputOutputStream
extends InputStream, OutputStream {
public void DoSomethingElse();
}
Cheers.
So. There are a lot of excellent answers here explaining in detail what an interface is. Yet, this is an example of its use, in the way one of my best colleagues ever explained it to me years ago, with what I have learned at university in the last couple of years mixed in.
An interface is a kind of 'contract'. It exposes some methods, fields and so on, that are available. It does not reveal any of its implementation details, only what it returns, and which parameters it takes. And in here lies the answer to question three, and what I feel is one of the greatest strengths of modern OOP:
"Code by addition, Not by modification" - Magnus Madsen, AAU
That's what he called it at least, and he may have it from some other place. The sample code below is written in C#, but everything shown can be done just about the same way in Java.
What we see is a class called SampleApp, that has a single field, the IOContext. IOContext is an interface.
SampleApp does not care one wit about how it saves its data, it just needs to do so, in its "doSomething()" method.
We can imagine that saving the data may have been more important than HOW it was saved at the beginning of the development process, so the developer chose to simply write the FileContext class. Later on, however, he needed to support JSON for whatever reason. So he wrote the JSONFileContext class, which inherits FileContext. This means that it is effectively an IOContext, which has the functionality of FileContext, save the replacement of FileContexts SaveData and LoadData, it still uses its 'write/read' methods.
Implementing the JSON class has been a small amount of work, comparing to writing the class, and having it just inherit IOContext.
The field of SampleApp could have been just of type 'FileContext', but that way, it would have been restricted to ever only using children of that class. By making the interface, we can even do the SQLiteContext implementation, and write to a database, SampleApp will never know or care, and when we have written the SQL lite class, we need only make one change to our code: new JSONFileContext(); instead becomes new SQLiteContext();
We still have our old implementations and can switch back to those if the need arises. We have broken nothing, and all the changes to our code are half a line, that can be changed back within the blink of an eye.
so: Code by addition, NOT by modification.
namespace Sample
{
class SampleApp
{
private IOContext context;
public SampleApp()
{
this.context = new JSONFileContext(); //or any of the other implementations
}
public void doSomething()
{
//This app can now use the context, completely agnostic of the actual implementation details.
object data = context.LoadData();
//manipulate data
context.SaveData(data);
}
}
interface IOContext
{
void SaveData(object data);
object LoadData();
}
class FileContext : IOContext
{
public object LoadData()
{
object data = null;
var fileContents = loadFileContents();
//Logic to turn fileContents into a data object
return data;
}
public void SaveData(object data)
{
//logic to create filecontents from 'data'
writeFileContents(string.Empty);
}
protected void writeFileContents(string fileContents)
{
//writes the fileContents to disk
}
protected string loadFileContents()
{
string fileContents = string.Empty;
//loads the fileContents and returns it as a string
return fileContents;
}
}
class JSONFileContext : FileContext
{
public new void SaveData(object data)
{
//logic to create filecontents from 'data'
base.writeFileContents(string.Empty);
}
public new object LoadData()
{
object data = null;
var fileContents = loadFileContents();
//Logic to turn fileContents into a data object
return data;
}
}
class SQLiteContext : IOContext
{
public object LoadData()
{
object data = null;
//logic to read data into the data object
return data;
}
public void SaveData(object data)
{
//logic to save the data object in the database
}
}
}
Interfaces
An interface is a contract defining how to interact with an object. They are useful to express how your internals intend to interact with an object. Following Dependency Inversion your public API would have all parameters expressed with interfaces. You don't care how it does what you need it to do, just that it does exactly what you need it to do.
Example: You may simply need a Vehicle to transport goods, you don't care about the particular mode of transport.
Inheritance
Inheritance is an extension of a particular implementation. That implementation may or may not satisfy a particular interface. You should expect an ancestor of a particular implementation only when you care about the how.
Example: You may need a Plane implementation of a vehicle for fast transport.
Composition
Composition can be used as an alternative to inheritance. Instead of your class extending a base class, it is created with objects that implement smaller portions of the main class's responsibility. Composition is used in the facade pattern and decorator pattern.
Example: You may create a DuckBoat (DUKW) class that implements LandVehicle and WaterVehicle which both implement Vehicle composed of Truck and Boat implementations.
Answers
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing any interface then it is inheritance ? We are not using its code.
Interfaces are not inheritance. Implementing an interface expresses that you intend for your class to operate in the way that is defined by the interface. Inheritance is when you have a common ancestor, and you receive the same behavior (inherit) as the ancestor so you do not need to define it.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritance ?
Interfaces do not achieve multiple inheritance. They express that a class may be suitable for multiple roles.
Q3. Anyhow what is the benefit of using Interfaces ? They are not having any code. We need to write code again and again in all classes we implement it.
One of the major benefits of interfaces is to provide separation of concerns:
You can write a class that does something with another class without caring how that class is implemented.
Any future development can be compatible with your implementation without needing to extend a particular base class.
In the spirit of DRY you can write an implementation that satisfies an interface and change it while still respecting the open/closed principal if you leverage composition.
Q1. As interfaces are having only abstract methods (no code) so how can we say that if we are implementing an interface then it is inheritance? We are not using its code.
It is not equal inheritance. It is just similiar. Let me explain:
VolvoV3 extends VolvoV2, and VolvoV2 extends Volvo (Class)
VolvoV3 extends VolvoV2, and VolvoV2 implements Volvo (Interface)
line1: Volvo v = new VolvoV2();
line2: Volvo v = new VolvoV3();
If you see only line1 and line2 you can infer that VolvoV2 and VolvoV3 have the same type. You cannot infer if Volvo a superclass or Volvo is an interface.
Q2. If implementing an interface is not inheritance then How interfaces are used to achieve multiple inheritances?
Now using interfaces:
VolvoXC90 implements XCModel and Volvo (Interface)
VolvoXC95 implements XCModel and Volvo (Interface)
line1: Volvo a = new VolvoXC90();
line2: Volvo a = new VolvoXC95();
line3: XCModel a = new VolvoXC95();
If you see only line1 and line2 you can infer that VolvoXC90 and VolvoXC95 have the same type (Volvo). You cannot infer that Volvo is a superclass or Volvo is an interface.
If you see only line2 and line3 you can infer that Volvo95 implements two types, XCModel and Volvo, in Java you know that at least one has to be an interface. If this code was written in C++, for instance, they could be both classes. Therefore, multiple inheritances.
Q3. Anyhow, what is the benefit of using Interfaces? They are not having any code. We need to write code again and again in all classes we implement it.
Imagine a system where you use a VolvoXC90 class in 200 other classes.
VolvoXC90 v = new VolvoXC90();
If you need to evolve your system to launch VolvoXC95 you have to alter 200 other classes.
Now, imagine a system where you use a Volvo interface in 10,000,000 classes.
// Create VolvoXC90 but now we need to create VolvoXC95
Volvo v = new VolvoFactory().newCurrentVolvoModel();
Now, if you need to evolve your system to create VolvoXC95 models you have to alter only one class, the Factory.
It is a common sense question. If your system is composed only of few classes and have few updates use Interfaces everywhere is counterproductive. For big systems, it can save you a lot of pain and avoid risk adopting Interfaces.
I recommend you read more about S.O.L.I.D principles and read the book Effective Java. It has good lessons from experienced software engineers.
Interfaces are made so that a class will implement the functionality within the interface and behave in accordance with that interface.

Why would both a parent and child class implement the same interface?

I inherited some legacy Java (1.4) code and this design decision appears regularly. I can't understand if there's any purpose or reason to it.
public interface SoapFacade extends iConfigurable{ }
public class SoapFacadeBase implements SoapFacade{
...
}
public class SoapFacadeImpl extends SoapFacadeBase implements SoapFacade{
...
}
As I understand interfaces (and my experimentation has reinforced), there is no purpose to having both the parent and the child implement the same interface. In this scenario, everything from SoapFacade is implemented in SoapFacadeBase, but the method in iConfigurable is implemented in SoapFacadeImpl. However, that doesn't create a need to have SoapFacadeImpl implement SoapFacade.
Is there something I don't know about interfaces that would give this pattern some purpose or benefit? Are there underlying costs beyond lack of clarity that should drive refactoring it? Or should it simply be refactored for clarity/simplicity?
As I understand interfaces (and my experimentation has reinforced), there is no purpose to having both the parent and the child implement the same interface.
No. Technically, it is completely redundant.
It does however document the fact that you intend SoapFacadeImpl to be a SoapFacade and it ensures that you get a compile error, if you (or someone else) decides to remove implements SoapFacade from the base class.
You see this pattern everywhere in the standard Java Collections API. ArrayList implements List even though its base class (AbstractList) already, does. Same holds for HashSet / AbstractSet and the Set interface.
If you use the interface also as a marker. Class.getInterfaces(); will only return directly instanced interfaces.
I actually find that design pointless. Implemented interfaces, as you stated, are just inherited, so there's no need to copy and paste "implements SomeInterface" on the children classes.
It's not clearer, smarter, or whatsoever...
It is nonsense, don't do it.
Especially in a public API like java collections. It's absolutely nonsense.

Disadvantage of object composition over class inheritance

Most design patten books say we should "Favor object composition over class inheritance."
But can anyone give me an example that inheritance is better than object composition.
Inheritance is appropriate for is-a relationships. It is a poor fit for has-a relationships.
Since most relationships between classes/components fall into the has-a bucket (for example, a Car class is likely not a HashMap, but it may have a HashMap), it then follows the composition is often a better idea for modeling relationships between classes rather than inheritance.
This is not to say however that inheritance is not useful or not the correct solution for some scenarios.
My simple answer is that you should use inheritance for behavioral purposes. Subclasses should override methods to change the behaviour of the method and the object itself.
This article (interview with Erich Gamma, one of the GoF) elaborates clearly why Favor object composition over class inheritance.
In Java, whenever you inherit from a class, your new class also automatically becomes a subtype of the original class type. Since it is a subtype, it needs to adhere to the Liskov substitution principle.
This principle basically says that you must be able to use the subtype anywhere where the supertype is expected. This severely limits how the behavior of your new inherited class can differ from the original class.
No compiler will be able to make you adhere to this principle though, but you can get in trouble if you don't, especially when other programmers are using your classes.
In languages that allow subclassing without subtyping (like the CZ language), the rule "Favor object composition over inheritance" is not as important as in languages like Java or C#.
Inheritance allows an object of the derived type to be used in nearly any circumstance where one would use an object of the base type. Composition does not allow this. Use inheritance when such substitution is required, and composition when it is not.
Just think of it as having an "is-a" or a "has-a" relationship
In this example Human "is-a" Animal, and it may inherits different data from the Animal class. Therefore Inheritance is used:
abstract class Animal {
private String name;
public String getName(){
return name;
}
abstract int getLegCount();
}
class Dog extends Animal{
public int getLegCount(){
return 4;
}
}
class Human extends Animal{
public int getLegCount(){
return 2;
}
}
Composition makes sense if one object is the owner of another object. Like a Human object owning a Dog object. So in the following example a Human object "has-a" Dog object
class Dog{
private String name;
}
class Human{
private Dog pet;
}
hope that helped...
It is a fundamental design principle of a good OOD. You can assign a behaviour to a class dynamicly "in runtime", if you use composition in your design rather than inheritance like in Strategy Pattern. Say,
interface Xable {
doSomething();
}
class Aable implements Xable { doSomething() { /* behave like A */ } }
class Bable implements Xable { doSomething() { /* behave like B */ } }
class Bar {
Xable ability;
public void setAbility(XAble a) { ability = a; }
public void behave() {
ability.doSomething();
}
}
/*now we can set our ability in runtime dynamicly */
/*somewhere in your code */
Bar bar = new Bar();
bar.setAbility( new Aable() );
bar.behave(); /* behaves like A*/
bar.setAbility( new Bable() );
bar.behave(); /* behaves like B*/
if you did use inheritance, the "Bar" would get the behaviour "staticly" over inheritance.
Inheritance is necessary for subtyping. Consider:
class Base {
void Foo() { /* ... */ }
void Bar() { /* ... */ }
}
class Composed {
void Foo() { mBase.Foo(); }
void Bar() { mBase.Foo(); }
private Base mBase;
}
Even though Composed supports all of the methods of Foo it cannot be passed to a function that expects a value of type Foo:
void TakeBase(Base b) { /* ... */ }
TakeBase(new Composed()); // ERROR
So, if you want polymorphism, you need inheritance (or its cousin interface implementation).
This is a great question. One I've been asking for years, at conferences, in videos, in blog posts. I've heard all kinds of answers. The only good answer I've heard is preformance:
Performance differences in languages. Sometimes, classes take advantage of built-in engine optimizations that dynamic compositions don't. Most of the time, this is a much smaller concern than the problems associated with class inheritance, and usually, you can inline everything you need for that performance optimization into a single class and wrap a factory function around it and get the benefits you need without a problematic class hierarchy.
You should never worry about this unless you detect a problem. Then you should profile and test differences in perf to make informed tradeoffs as needed. Often, there are other performance optimizations available that don't involve class inheritance, including tricks like inlining, method delegation, memoizing pure functions, etc... Perf will vary depending on the specific application and language engine. Profiling is essential, here.
Additionally, I've heard lots of common misconceptions. The most common is confusion about type systems:
Conflating types with classes (there are a couple existing answers concentrate on that here already). Compositions can satisfy polymorphism requirements by implementing interfaces. Classes and types are orthogonal, though in most class-supporting languages, subclasses automatically implement the superclass interface, so it can seem convenient.
There are three very good reasons to avoid class inheritance, and the crop up again and again:
The gorilla/banana problem
"I think the lack of reusability comes in object-oriented languages, not functional languages. Because the problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle." ~ Joe Armstrong, quoted in "Coders at Work" by Peter Seibel.
This problem basically refers to the lack of selective code reuse in class inheritance. Composition lets you select just the pieces you need by approaching software design from a "small, reusable parts" approach rather than building monolithic designs that encapsulate everything related to some given functionality.
The fragile base class problem
Class inheritance is the tightest coupling available in object-oriented design, because the base class becomes part of the implementation of the child classes. This is why you'll also hear the advice from the Gang of Four's "Design Patterns" classic: "Program to an interface, not an implementation."
The problem with implementation inheritance is that even the smallest change to the inner details of that implementation could potentially break child classes. If the interface is public, exposed to user-land in any way, it could break code you are not even aware of.
This is the reason that class hierarchies become brittle -- hard to change as you grow them with new use-cases.
The common refrain is that we should be constantly refactoring our code (see Martin Fowler et al on extreme programming, agile, etc...). The key to refactor success is that you can't break things -- but as we've just seen, it's difficult to refactor a class hierarchy without breaking things.
The reason is that it's impossible to create the correct class hierarchy without knowing everything you need to know about the use-cases, but you can't know that in evolving software. Use cases get added or changed in projects all the time.
There is also a discovery process in programming, where you discover the right design as you implement the code and learn more about what works and what doesn't. But with class inheritance, once you get a class taxonomy going, you've painted yourself into a corner.
You need to know the information before you start the implementation, but part of learning the information you need involves building the implementation. It's a catch-22.
The duplication by necessity problem. This is where the death spiral really gets going. Sometimes, you really just want a banana, not the gorilla holding the banana, and the entire jungle. So you copy and paste it. Now there's a bug in a banana, so you fix it. Later, you get the same bug report and close it. "I already fixed that". And then you get the same bug report again. And again. Uh-oh. It's not fixed. You forgot the other banana! Google "copy pasta".
Other times, you really need to work a new use-case into your software, but you can't change the original base class, so instead, you copy and paste the entire class hierarchy into a new one and rename all the classes you need in the hierarchy to force that new use-case into the code base. 6 months later a new dev is looking at the code and wondering which class hierarchy to inherit from and nobody can provide a good answer.
Duplication by necessity leads to copy pasta messes, and pretty soon people start throwing around the word "rewrite" like it's no big deal. The problem with that is that most rewrite projects fail. I can name several orgs off the top of my head that are currently maintaining two development teams instead of one while they work on a rewrite project. I've seen such orgs cut funding to one or the other, and I've seen projects like that chew through so much cash that a startup or small business runs out of money and shuts down.
Developers underestimate the impact of class inheritance all the time. It's an important choice, and you need to be aware of the trade offs you opt into every time you create or inherit from a base class.

Categories

Resources