I've seen in several code libraries classes named Mixin with comments like:
//Mixin style implementation
public class DetachableMixin implements Detachable {}
Which is the concept under this style of implementations?
Here is a qoute from Joshua Bloch "Efective Java" (I don't think, I could explain it better myself):
Interfaces are ideal for defining mixins. Loosely speaking, a mixin is a type
that a class can implement in addition to its “primary type” to declare that it provides
some optional behavior. For example, Comparable is a mixin interface that
allows a class to declare that its instances are ordered with respect to other mutually
comparable objects. Such an interface is called a mixin because it allows the
optional functionality to be “mixed in” to the type’s primary functionality.
Abstract classes can’t be used to define mixins for the same reason that they can’t
be retrofitted onto existing classes: a class cannot have more than one parent, and
there is no reasonable place in the class hierarchy to insert a mixin.
The other answer is spot on, but it might be worth pointing out that other JVM languages go even further.
Scala for examples has traits - basically "interfaces" with method implementations. In scala, you can mix one class together with multiple traits, thereby allowing to inherit behavior from several different "places.
Basically the same concept that Java picked up with Java 8, where you know can add default method behavior to interfaces. And for the record: if I recall it correctly, Java8 interfaces and default methods are not meant to introduce a full "mixin" concept in the Java language. The idea is not that you should use this feature to achieve multiple inheritance through the back door. See this lengthy answer from Stuart Mark, one of the people driving the Java language evolution. They state:
The purpose of default methods ... is to enable interfaces to be evolved in a compatible manner after their initial publication.
A good article about implementing mixin pattern with Virtual Extension Methods since Java 8: https://kerflyn.wordpress.com/2012/07/09/java-8-now-you-have-mixins/
The virtual extension method is something new in Java. It brings another mean of expression to create new patterns and best pratices. This article provides an example of such a pattern, enabled in Java 8 due to the use of virtual extension methods. I am sure you can extract other new patterns from them. But, as I have experienced here, you should not hesitate to share them in a view to check their validaty.
I have this confusion for long time. Many people says we can achieve multiple inheritance by interfaces in languages like C# or Java which does not support it like C++ does. But my understanding of inheritance and interface says no. Because interfaces are contracts to validate an implementation which has nothing to do with behavior. Interface defines what something can do (not what something is). But inheritance is inheriting behavior and/or property from parents (like a child is getting some genetic behavior from his parent - which is inheritance). Now the child is learning a skills say painting and cooking and the interface (a certificate or contract) acts as a validation that the child is having such skills (that is what the child can do other than what he got from his parents - and that's not inheritance)
So am I understanding it wrong? And if not then why it is saying that we can achieve multiple inheritance using interfaces?
Interfaces give you multiple inheritance of a type, but not behaviour. A class implementing List and Map is a "ListMap", but the implementation has nothing (necessarily) to do with any existing List or Map implementation.
Of course using composition (which should be favored anyways), you could easily create a ListMap which delegates the calls accordingly to its list and map properties, while providing some presumably useful function that would combine their respective data.
With Java 8 interfaces are allowed default methods, so inheritance of behaviour is now also possible.
In Java you can create an interface for example Animal and an abstract class Bird.
then you can have a class MockingBird which extends the behavior of Bird and implements the actions of an Animal.
However, you can then address MockingBird as an Animal or as a Bird because it "inherits" from both.
No, interfaces cannot be used to achieve multiple inheritance
Not at all in Java, in C#, we can get closer.
I studied this matter when I wanted to implement an observer, and ended up in Robert Martin's blog: http://blog.cleancoder.com/uncle-bob/2015/01/08/InterfaceConsideredHarmful.html
After reading this post I realized he's talking about Java, but C# supports extension methods which allow you to attach behaviour on interfaces so I tried to make my implementation on some IObservable interface but obviously failed, even if I can attach behaviour in such interfaces extension methods I'm still not allowed for attaching state on them, if some day microsoft decides to implement extension properties then this combination (Interface + Extension methods + Extension properties) could be sufficient to truly simulate some useful multiple inheritance.
For now, we are stuck with duplicating the code, or the delegation code in all our observers as stated in the blog.
Well I was going to ask what the difference is but it's been answered before. But now I'm asking why did they make these differences? (I'm speaking about java here, I don't know if the same applies to other languages)
The two things seem very similar. Abstract classes can define a method body whilst interfaces can't, but multiple interfaces can be inherited. So why didn't they (by 'they' I mean Sun when they wrote Java) make one thing where you can write a method body and this type can be inherited more than once by a class.
Is there some advantage in not being able to write a method body, or extend multiple times that I'm not seeing?
Because allowing classes to inherit multiple implementations for the same method signature leads to the obvious question, which one should be used at runtime.
Java avoids this by supporting multiple inheritance only for interfaces. The signatures declared in each interface can be combined much more easily (Java basically uses the union of all methods)
Multiple inheritance in C++ leads to semantic ambiguities like the diamond inheritance problem. MI is quite powerful, but has complex consequences.
Making interfaces a special case also raises the visibility of the concept as a means of information hiding and reducing program complexity. In C++, defining pure abstract bases is a sign of a mature programmer. In Java, you encounter them at a much earlier stage in the evolution of a programmer.
Multiple inheritance is more difficult to implement in a language (compiler really) as it can lead to certain issues. These issues have been discussed here before: What is the exact problem with multiple inheritance.
I've always assumed this was a compromise in Java. Interfaces allow a class to fulfill multiple contracts without the headache of multiple inheritance.
Consider this example:
public abstract class Engine
{
public abstract void switchPowerOn();
public abstract void sprinkleSomeFuel();
public abstract void ignite();
public final void start()
{
switchPowerOn();
sprinkleSomeFuel();
ignite();
}
}
Abstract class can help you with having solid base methods which can or cannot be overriden, but in these methods it uses abstract methos to provide you an opportunity to do your specific thing. In my example different engines have different implementations of how they switch power on, sprinkling some fuel for the ignition, and doing the ignition, however the starting sequence of the engine stays always the same.
That pattern is called "Form Template Method" and is quite frankly the only sensible usage of abstract classes in Java for me.
Making them one thing is the route that the Scala guys took with Traits which is an interface that can have methods and supports multiple inheritance.
I think interfaces, for me, are clean in that they only specify requirements (design by contract) whereas abstract classes define common behaviour (implementation), so a different tool for a different job? Interfaces probably allow more efficient code generation during compile time as well?
The other approach you are describing is the approach used by C++ (mixins for example). The issues related to such "multiple inheritance" are quite complex, and has several critics in C++.
Inheritance means you inherit the nature (meaning) and responsibility (behaviour) of the parent class, while interface implementation means you fulfill a contract (e.g. Serializable), which may have nothing to do with the core nature or responsibility of the class.
Abstract class let you define a nature that you want to be generic and not directly instanciable, because it must be specialized. You know how to perform some high-level tasks (e.g. make a decision according to some parameters), but you don't know the details for some lower-level actions (e.g. compute some intermediary parameters), because it depends on implementation choices. An alternative for solving this problem is the Strategy design pattern. It is more flexible, allowing run-time strategy switching and Null behaviour, yet it is more complex (and runtime swtiching is not always necessary). Moreover, you might lose some meaning & typing facilities (polymorphism & type-checking becomes a bit harder because the Strategy is a component, not the object itself).
Abstract class = is-a, Strategy = has-a
Edit: as for multiple inheritance, see Pontus Gagge's answer.
I recently attended an interview and they asked me the question "Why Interfaces are preferred over Abstract classes?"
I tried giving a few answers like:
We can get only one Extends functionality
they are 100% Abstract
Implementation is not hard-coded
They asked me take any of the JDBC api that you use. "Why are they Interfaces?".
Can I get a better answer for this?
That interview question reflects a certain belief of the person asking the question. I believe that the person is wrong, and therefore you can go one of two directions.
Give them the answer they want.
Respectfully disagree.
The answer that they want, well, the other posters have highlighted those incredibly well.
Multiple interface inheritance, the inheritance forces the class to make implementation choices, interfaces can be changed easier.
However, if you create a compelling (and correct) argument in your disagreement, then the interviewer might take note.
First, highlight the positive things about interfaces, this is a MUST.
Secondly, I would say that interfaces are better in many scenarios, but they also lead to code duplication which is a negative thing. If you have a wide array of subclasses which will be doing largely the same implementation, plus extra functionality, then you might want an abstract class. It allows you to have many similar objects with fine grained detail, whereas with only interfaces, you must have many distinct objects with almost duplicate code.
Interfaces have many uses, and there is a compelling reason to believe they are 'better'. However you should always be using the correct tool for the job, and that means that you can't write off abstract classes.
In general, and this is by no means a "rule" that should be blindly followed, the most flexible arrangement is:
interface
abstract class
concrete class 1
concrete class 2
The interface is there for a couple of reasons:
an existing class that already extends something can implement the interface (assuming you have control over the code for the existing class)
an existing class can be subclasses and the subclass can implement the interface (assuming the existing class is subclassable)
This means that you can take pre-existing classes (or just classes that MUST extend from something else) and have them work with your code.
The abstract class is there to provide all of the common bits for the concrete classes. The abstract class is extended from when you are writing new classes or modifying classes that you want to extend it (assuming they extend from java.lang.Object).
You should always (unless you have a really good reason not to) declare variables (instance, class, local, and method parameters) as the interface.
You only get one shot at inheritance. If you make an abstract class rather than an interface, someone who inherits your class can't also inherit a different abstract class.
You can implement more than one interface, but you can only inherit from a single class
Abstract Classes
1.Cannot be instantiated independently from their derived classes. Abstract class constructors are called only by their derived classes.
2.Define abstract member signatures that base classes must implement.
3.Are more extensible than interfaces, without breaking any version compatibility. With abstract classes, it is possible to add additional nonabstract members that all derived classes can inherit.
4.Can include data stored in fields.
5.Allow for (virtual) members that have implementation and, therefore, provide a default implementation of a member to the deriving class.
6.Deriving from an abstract class uses up a subclass's one and only base class option.
Interface
1.Cannot be instantiated.
2.Implementation of all members of the interface occurs in the base class. It is not possible to implement only some members within the implementing class.
3.Extending interfaces with additional members breaks the version compatibility.
4.Cannot store any data. Fields can be specified only on the deriving classes. The workaround for this is to define properties, but without implementation.
5.All members are automatically virtual and cannot include any implementation.
6.Although no default implementation can appear, classes implementing interfaces can continue to derive from one another.
As devinb and others mention, it sounds like the interviewer shows their ignorance in not accepting your valid answers.
However, the mention of JDBC might be a hint. In that case, perhaps they are asking for the benefits of a client coding against an interface instead of a class.
So instead of perfectly valid answers such as "you only get one use of inheritance", which are relating to class design, they may be looking for an answer more like "decouples a client from a specific implementation".
Abstract classes have a number of potential pitfalls. For example, if you override a method, the super() method is not called unless you explicitly call it. This can cause problems for poorly-implemented overriding classes. Also, there are potential problems with equals() when you use inheritance.
Using interfaces can encourage use of composition when you want to share an implementation. Composition is very often a better way to reuse others objects, as it is less brittle. Inheritance is easily overused or used for the wrong purposes.
Defining an interface is a very safe way to define how an object is supposed to act, without risking the brittleness that can come with extending another class, abstract or not.
Also, as you mention, you can only extend one class at a time, but you can implement as many interfaces as you wish.
Abstract classes are used when you inherit implementation, interfaces are used when you inherit specification. The JDBC standards state that "A connection must do this". That's specification.
When you use abstract classes you create a coupling between the subclass and the base class. This coupling can sometimes make code really hard to change, especially as the number of subclasses increases. Interfaces do not have this problem.
You also only have one inheritance, so you should make sure you use it for the proper reasons.
"Why Interfaces are preferred over
Abstract classes?"
The other posts have done a great job of looking at the differences between interfaces and abstract classes, so I won't duplicate those thoughts.
But looking at the interview question, the better question is really "When should interfaces be preferred over abstract classes?" (and vice versa).
As with most programming constructs, they're available for a reason and absolute statements like the one in the interview question tend to miss that. It sort of reminds me of all the statement you used to read regarding the goto statement in C. "You should never use goto - it reveals poor coding skills." However, goto always had its appropriate uses.
Respectfully disagree with most of the above posters (sorry! mod me down if you want :-) )
First, the "only one super class" answer is lame. Anyone who gave me that answer in an interview would be quickly countered with "C++ existed before Java and C++ had multiple super classes. Why do you think James Gosling only allowed one superclass for Java?"
Understand the philosophy behind your answer otherwise you are toast (at least if I interview you.)
Second, interfaces have multiple advantages over abstract classes, especially when designing interfaces. The biggest one is not having a particular class structure imposed on the caller of a method. There is nothing worse than trying to use a method call that demands a particular class structure. It is painful and awkward. Using an interface anything can be passed to the method with a minimum of expectations.
Example:
public void foo(Hashtable bar);
vs.
public void foo(Map bar);
For the former, the caller will always be taking their existing data structure and slamming it into a new Hashtable.
Third, interfaces allow public methods in the concrete class implementers to be "private". If the method is not declared in the interface then the method cannot be used (or misused) by classes that have no business using the method. Which brings me to point 4....
Fourth, Interfaces represent a minimal contract between the implementing class and the caller. This minimal contract specifies exactly how the concrete implementer expects to be used and no more. The calling class is not allowed to use any other method not specified by the "contract" of the interface. The interface name in use also flavors the developer's expectation of how they should be using the object. If a developer is passed a
public interface FragmentVisitor {
public void visit(Node node);
}
The developer knows that the only method they can call is the visit method. They don't get distracted by the bright shiny methods in the concrete class that they shouldn't mess with.
Lastly, abstract classes have many methods that are really only present for the subclasses to be using. So abstract classes tend to look a little like a mess to the outside developer, there is no guidance on which methods are intended to be used by outside code.
Yes of course some such methods can be made protected. However, sadly protected methods are also visible to other classes in the same package. And if an abstract class' method implements an interface the method must be public.
However using interfaces all this innards that are hanging out when looking at the abstract super class or the concrete class are safely tucked away.
Yes I know that of course the developer may use some "special" knowledge to cast an object to another broader interface or the concrete class itself. But such a cast violates the expected contract, and the developer should be slapped with a salmon.
If they think that X is better than Y I wouldn't be worried about getting the job, I wouldn't like working for someone who forced me to one design over another because they were told interfaces are the best. Both are good depending on the situation, otherwise why did the language choose to add abstract classes? Surely, the language designers are smarter than me.
This is the issue of "Multiple Inheritance".
We can "extends" not more than one abstarct class at one time through another class but in Interfaces, we can "implement" multiple interfaces in single class.
So, though Java doesn't provide multiple inheritance in general but by using interfaces we can incorporate multiplt inheritance property in it.
Hope this helps!!!
interfaces are a cleaner way of writing a purely abstract class. You can tell that implementation has not sneaked in (of course you might want to do that at certain maintenance stages, which makes interfaces bad). That's about it. There is almost no difference discernible to client code.
JDBC is a really bad example. Ask anyone who has tried to implement the interfaces and maintain the code between JDK releases. JAX-WS is even worse, adding methods in update releases.
There are technical differences, such as the ability to multiply "inherit" interface. That tends to be the result of confused design. In rare cases it might be useful to have an implementation hierarchy that is different from the interface hierarchy.
On the downside for interfaces, the compiler is unable to pick up on some impossible casts/instanceofs.
There is one reason not mentioned by the above.
You can decorate any interface easily with java.lang.reflect.Proxy allowing you to add custom code at runtime to any method in the given interface. It is very powerful.
See http://tutorials.jenkov.com/java-reflection/dynamic-proxies.html for a tutorial.
interface is not substitute for abstract class.
Prefer
interface: To implement a contract by multiple unrelated objects
abstract class: To implement the same or different behaviour among multiple related objects
Refer to this related SE question for use cases of both interface and abstract class
Interface vs Abstract Class (general OO)
Use case:
If you have to use Template_method pattern, you can't achieve with interface. Abstract class should be chosen to achieve it.
If you have to implement a capability for many unrleated objects, abstract class does not serve the purpose and you have to chose interface.
You can implement multiple interfaces, but particularly with c# you can not have multiple inheritances
Because interfaces are not forcing you into some inheritance hierarchy.
You define interfaces when you only require that some object implement certain methods but you don't care about its pedigree. So someone can extend an existing class to implement an interface, without affecting the previously existing behavior of that class.
That's why JDBC is all interfaces; you don't really care what classes are used in a JDBC implementation, you only need any JDBC implementation to have the same expected behavior. Internally, the Oracle JDBC driver may be very different from the PostgreSQL driver, but that's irrelevant to you. One may have to inherit from some internal classes that the database developers already had, while another one may be completely developed from scratch, but that's not important to you as long as they both implement the same interfaces so that you can communicate with one or the other without knowing the internal workings of either.
Well, I'd suggest the question itself should be rephrased. Interfaces are mainly contracts that a class acquires, the implementation of that contract itself will vary. An abstract class will usually contain some default logic and its child classes will add some more logic.
I'd say that the answer to the questions relies on the diamond problem. Java prevents multiple inheritance to avoid it. ( http://en.wikipedia.org/wiki/Diamond_problem ).
They asked me take any of the JDBC api
that you use. "Why are they
Interfaces?".
My answer to this specific question is :
SUN doesnt know how to implement them or what to put in the implementation. Its up to the service providers/db vendors to put their logic into the implementation.
The JDBC design has relationship with the Bridge pattern, which says "Decouple an abstraction from its implementation so that the two can vary independently".
That means JDBC api's interfaces hierarchy can be evolved irrespective of the implementation hierarchy that a jdbc vendor provides or uses.
Abstract classes offer a way to define a template of behavior, where the user plugins in the details.
One good example is Java 6's SwingWorker. It defines a framework to do something in the background, requiring the user to define doInBackground() for the actual task.
I extended this class such that it automatically created a popup progress bar. I overrode done(), to control disposal of this pop-up, but then provided a new override point, allowing the user to optionally define what happens after the progress bar disappears.
public abstract class ProgressiveSwingWorker<T, V> extends SwingWorker<T, V> {
private JFrame progress;
public ProgressiveSwingWorker(final String title, final String label) {
SwingUtilities.invokeLater(new Runnable() {
#SuppressWarnings("serial")
#Override
public void run() {
progress = new JFrame() {{
setLayout(new MigLayout("","[grow]"));
setTitle(title);
add(new JLabel(label));
JProgressBar bar = new JProgressBar();
bar.setIndeterminate(true);
add(bar);
pack();
setLocationRelativeTo(null);
setVisible(true);
}};
}
});
}
/**
* This method has been marked final to secure disposing of the progress dialog. Any behavior
* intended for this should be put in afterProgressBarDisposed.
*/
#Override
protected final void done() {
progress.dispose();
try {
afterProgressBarDisposed(get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
protected void afterProgressBarDisposed(T results) {
}
}
The user still has the requirement of providing the implementation of doInBackground(). However, they can also have follow-up behavior, such as opening another window, displaying a JOptionPane with results, or simply do nothing.
To use it:
new ProgressiveSwingWorker<DataResultType, Object>("Editing some data", "Editing " + data.getSource()) {
#Override
protected DataResultType doInBackground() throws Exception {
return retrieve(data.getSource());
}
#Override
protected void afterProgressBarDisposed(DataResultType results) {
new DataEditor(results);
}
}.execute();
This shows how an abstract class can nicely provide a templated operation, orthogonal to the concept of interfaces defining an API contract.
Its depend on your requirement and power of implementation, which is much important.
You have got so many answer regarding this question.
What i think about this question is that abstract class is the evolution if API.
You can define your future function definition in abstract class but you don't need all function implementation in your main class but with interface you cant do this thing.