38

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?

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
Techmaddy
  • 4,586
  • 5
  • 28
  • 33
  • 1
    I'm almost sure I've seen a question like this before, but not even Google can find it. Maybe my mind is playing tricks on me again. – Michael Myers Mar 12 '09 at 17:22
  • Note: I edited the title for grammar; I left the body since it seems to be quotations, and maybe they did say it like that. – Michael Myers Mar 12 '09 at 17:28
  • This is a loaded question, since it assumes a position on the topic and gives no context in which it 'may' be valid. I agree with devinb on this one. They are both tools - use them appropriately. Too many answers here justify the question...which may be acceptable if you really want the job. – Robin Mar 12 '09 at 18:17
  • 3
    Don't justify the question with an answer. That isn't what they are (well, should be) looking for. Show that you know what you are talking about, and can do the job. If they are worth working for, they aren't looking for a parrot. – Adam Jaskiewicz Mar 13 '09 at 12:16
  • See my full comment below .. but anytime I get an answer like yours, the candidate gets a frosty "thank-you-for-your-time". The answer shows no depth of understanding. – Pat Mar 15 '09 at 07:44
  • Start writing testcases or go the TDD route and you'll find that writing testcases is far more easier when using interfaces. It allows you to mock out everything you don't need for your testcase. – Lieven Keersmaekers Nov 25 '09 at 13:24
  • possible duplicate of [Interface vs Abstract Class (general OO)](http://stackoverflow.com/questions/761194/interface-vs-abstract-class-general-oo) – RAS Jul 01 '13 at 07:19
  • Possible duplicate of [When to use an interface instead of an abstract class and vice versa?](http://stackoverflow.com/questions/479142/when-to-use-an-interface-instead-of-an-abstract-class-and-vice-versa) – Ravindra babu Sep 18 '16 at 18:49

23 Answers23

55

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.

  1. Give them the answer they want.
  2. 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.

DevinB
  • 8,231
  • 9
  • 44
  • 54
  • 3
    If you respectfully disagree, I think you've almost certainly thrown away the chance of getting the job. – Tom Hawtin - tackline Mar 12 '09 at 17:36
  • 30
    If your interviewer is close-minded and unwilling to hear an alternate viewpoint, then I wouldn't want the job. As long as you're respectful (and you understand the chain of command) you should be able to give a valid, thoughtful opinion, and not be punished for it. – DevinB Mar 12 '09 at 18:02
  • 1
    I would +1 more than once if I could. Only answer I have seen so far that (appropriately) challenges the question. A better question would have been "When are interfaces preferred over Abstract classes", or "name the pros and cons of interfaces and abstract classes". – Robin Mar 12 '09 at 18:20
  • 4
    @Tom depending on how you present it, it should not cost you the chance at the job. On the other hand if it does than perhaps you didn't really want to work there anyways :-) – TofuBeer Mar 12 '09 at 18:26
  • 8
    This question does not mean that it is what the interviewer believes. They may think differently, but want to see whether you agree with them or have the bottle to challenge a question. It's common for loaded questions to be answered when the job opening is competitive. – Mike B Mar 29 '09 at 16:29
  • 1
    Interfaces would not lead to code duplication, if you have two objects with the same functionality that implies the same API and hence same interface. Abstract classes are implementation details, while interfaces are a general contract you expose to the programmer using your API. – Christopher Perry Sep 21 '13 at 20:29
  • The problem with this solution that you have read the question with your ego. Interviewer asked why is it preferred, not why is it preferred all the time. – flash42 Jun 08 '19 at 07:41
25

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.

TofuBeer
  • 60,850
  • 18
  • 118
  • 163
  • 1
    Well put. The list and collection interfaces and classes have numerous examples of this. – Robin Mar 12 '09 at 18:23
  • This is a very powerful and flexible pattern. I've seen it used a lot in frameworks. Effectively the abstract class provides a 'skeleton' implementation of the interface. – Andrew Fielden Mar 13 '09 at 11:52
  • It may be worth noting that (1) any concrete class which inherits form the abstract class cannot inherit from anything else--a restriction which may not seem likely to be a problem, but which could be; the ability to implement the interface directly provides a "safety valve" in case a situation arises where class inheritance would be problematic; (2) classes which implement the interface directly *will* have to be changed if the interface changes; if the base class can do things like offer default implementation of new methods, classes derived from it may not have to change. – supercat Oct 31 '12 at 17:25
  • If one ends up with an interface that gets implemented directly by three classes (including the abstract base class), and that base class gets inherited by a dozen other classes, adding the intermediate layer may mean that changing the interface requires fixing three classes, rather than fourteen. A pretty big win. It's worth noting, however, that things like variables and storage locations should be declared to be of the interface type rather than the abstract type, so as to allow classes that implement the interface directly to interact with those that inherit the abstract base. – supercat Oct 31 '12 at 17:26
23

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.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
10

You can implement more than one interface, but you can only inherit from a single class

Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166
9

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.

Warrior
  • 39,156
  • 44
  • 139
  • 214
7

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

Community
  • 1
  • 1
toolkit
  • 49,809
  • 17
  • 109
  • 135
5

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.

Eddie
  • 53,828
  • 22
  • 125
  • 145
4

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.

paulmurray
  • 3,355
  • 1
  • 22
  • 17
3

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.

krosenvold
  • 75,535
  • 32
  • 152
  • 208
3

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

Neal Stublen
  • 815
  • 11
  • 14
3

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.

Pat
  • 5,761
  • 5
  • 34
  • 50
  • The question you'd counter with is better than the original, IMHO, though one might phrase it in terms of "many recent languages and frameworks" rather than Java in particular. While .net does borrow some rather silly things from Java (e.g. the notion that floats should implicitly convert to doubles, but not vice versa, when float-to-double conversions are more likely to be erroneous) I don't think .net has single inheritance simply because Java does. Inheritance is useful for both code/data shsaring and substitutability. Code/data sharing is often more convenient with... – supercat Feb 26 '12 at 19:34
  • ...inheritance than with composition, though it can be achieved either way. Allowing a form of multiple inheritance that includes code/data sharing introduces difficulties (e.g. the "diamond problem"). Since multiple inheritance of code/data doesn't allow much that can't be achieved via composition, but the ability for things to be substitutable for multiple other things that are unrelated to each other is very useful, it makes sense to offer something that's like inheritance, but is restricted to the latter functionality. – supercat Feb 26 '12 at 19:38
  • (BTW, wrt floats and doubles, multiplying two doubles which equal 1E38, and then casting the result to a float, will yield an answer meaning "Number to big for a float", which will be correct. Multiplying two floats which equal 1E38, and then casting the result to a double, will yield "answer too big for a double", which will be incorrect. – supercat Feb 26 '12 at 19:41
2

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

Marco167
  • 371
  • 3
  • 7
2

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.

scott
  • 974
  • 7
  • 10
1

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.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
1

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.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
0

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.

gregturn
  • 2,625
  • 3
  • 25
  • 40
0

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.

Pankaj
  • 4,419
  • 16
  • 50
  • 72
0

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.

Community
  • 1
  • 1
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
0

You can implement multiple interfaces, but particularly with c# you can not have multiple inheritances

user68610
  • 169
  • 4
0

Because interfaces are not forcing you into some inheritance hierarchy.

Marko
  • 30,263
  • 18
  • 74
  • 108
0

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.

Chochos
  • 5,155
  • 22
  • 27
  • So if JDBC was all pure abstract classes, how would that differ? (Leaving aside that the interfaces have changed between releases.) – Tom Hawtin - tackline Mar 12 '09 at 17:52
  • @Tom Hawtin: I told the same and they asked what Tom Hawtin asked. – Techmaddy Mar 12 '09 at 18:10
  • If it were abstract classes instead of interfaces it might be faster depending on the VM, and it would force implementors to extend only from the classes that were given to them as part of the java.sql libraries, which could be limiting. – TofuBeer Mar 12 '09 at 23:22
0

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

Yorch
  • 21
  • 2
0

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.

Manoj
  • 364
  • 1
  • 2
  • 8