views:

2420

answers:

22

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?

+21  A: 

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
Hi, that's true. But he can still inherit an interface, can't he?
Bryan
That's the point of the answer.
DJClayworth
+8  A: 

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

Rowland Shaw
I gave this answer and they expected something else.
Techmaddy
In that case, I wouldn't be too upset if they didn't give you an offer ;)
Rowland Shaw
This is like the first answer that I gave and there are a few others as I specified in the description. I am worried if there is something else that I am missing.
Techmaddy
Maybe they are testing your confidence ;-)
Ryan Graham
Why the recent downvote, without comment?
Rowland Shaw
+3  A: 

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
A: 

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

+1  A: 

I think the better question is why not? Why use something more complicated and restrictive like an abstract class when an interface is all that is needed?

Spencer Ruport
+4  A: 

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
+8  A: 

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
A: 

Because interfaces are not forcing you into some inheritance hierarchy.

Dev er dev
+37  A: 

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.

If you respectfully disagree, I think you've almost certainly thrown away the chance of getting the job.
Tom Hawtin - tackline
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.
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
@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
+1 since robin can't :-) (and I like the answer)
TofuBeer
+1, for the great answer :-)
Darin Dimitrov
+1 for a nicely considered answer
David Hall
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.
EnderMB
+1  A: 

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
+17  A: 

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
Well put. The list and collection interfaces and classes have numerous examples of this.
Robin
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.
Hicks
+7  A: 

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

toolkit
A: 

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
So if JDBC was all pure abstract classes, how would that differ? (Leaving aside that the interfaces have changed between releases.)
Tom Hawtin - tackline
@Tom Hawtin: I told the same and they asked what Tom Hawtin asked.
Techmaddy
Should that be @Chochos?
Tom Hawtin - tackline
@Tom Hawtin: ya..
Techmaddy
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
+3  A: 

"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 S.
+4  A: 

"They aren't; both have their uses, and the answer depends on what you are trying to do. Could you be more specific, please?"

Adam Jaskiewicz
A: 

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
+1  A: 

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
+1  A: 

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
+3  A: 

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
A: 

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
A: 

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
A: 

Hello Techmaddy, 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