8

To achieve multiple inheritance, we must use interfaces, but why don't interface methods have bodies and why do they have to be overridden in the derived class?

I really want a lucid answer , not involving too much computer jargon , i cant seem to understand this , i have referred various references

Nishant Jani
  • 1,965
  • 8
  • 30
  • 41
  • 3
    because otherwise you would have got the mess of regular (C++ like) multiple inheritance, which is usually redundant complexation. – amit Aug 31 '12 at 05:37
  • i was asked this at an interview , could you please elaborate this – Nishant Jani Aug 31 '12 at 05:38
  • 2
    Interfaces are *not* "multiple inheritance". Multiple inheritance is ugly, interfaces are beautiful ;) And interfaces aren't *overridden*, they're "implemented". To understand Java "interfaces", you need to understand "OO polymorphism". A Java interfaces is a CONTRACT which a implementing class must HONOR. A Java interfaces is "specification"; an implementing class provides the actual "behavior". – paulsm4 Aug 31 '12 at 05:38
  • "i was asked this at an interview". If you're accurately stating what the interviewer actually said ... I would have corrected him (or her) ... and then RUN! IMHO... – paulsm4 Aug 31 '12 at 05:42
  • @paulsm4 what is the correction in the question !! (excited) – Nishant Jani Aug 31 '12 at 05:44
  • Also if interface had method bodies, how would it provide Abstraction? – Nandkumar Tekale Aug 31 '12 at 06:11
  • @Nandkumar could you elaborate a little please – Nishant Jani Aug 31 '12 at 06:34
  • @user1537158 : http://chat.stackoverflow.com/rooms/15943/discussion-between-nandkumar-and-anuj-balan – Nandkumar Tekale Aug 31 '12 at 06:41

8 Answers8

13

Because Java, in contrast to languages like C++ or Eiffel, only has multiple inheritance of types (i.e. interfaces as well as one class), not multiple inheritance of state and behaviour. The latter of which add enormous complexity (especially state).

The Java designers (and C#, for that matter) opted to not include it as it presented C++ programmers often with very hard to debug issues. You can solve pretty much most problems that require true multiple inheritance with implementing multiple interfaces, so the tradeoff was deemed worth it.

Note that multiple inheritance of behaviour (not state) might come to Java 8 (unless they postpone it again like one of the many other things) in form of virtual extension methods where an interface can declare a method that delegates to one in another class, which then exists on all types that implement that interface.

Joey
  • 344,408
  • 85
  • 689
  • 683
  • could be more specific about types and behaviour , giving some example ? please – Nishant Jani Aug 31 '12 at 06:25
  • 1
    If you have a class, it will invariably have *state*, i.e. fields. E.g. for a hypothetical `Person` class that might be a name. Then classes have *behaviour* in form of methods. Methods do certain things and in a certain way. Interfaces in contrast only state the name and arguments of methods in sort of a contract. How an implementing class implements those methods is up to the class, thus the interface cannot provide behaviour since it doesn't have an implementation of the method. – Joey Aug 31 '12 at 06:29
  • by that you mean , each derived class in java , that implements a interface , will then have a flexibility of having its own defination of a method in the interface? – Nishant Jani Aug 31 '12 at 06:36
  • 1
    It can implement the method however it sees fit, yes. That's why both a LinkedList and an ArrayList have a `get(int)` method, but for both it is implemented quite differently. – Joey Aug 31 '12 at 07:33
2

Interfaces declare WHAT services the implementing class provides, not HOW (that's the job of the implementing class). Multiple inheritance is regarded bad, as it leads to complicated code and class hierarchies.

esaj
  • 15,875
  • 5
  • 38
  • 52
2

Interfaces only have constant variables(public + static + final) and abstract methods(public & abstract). These are meant to be used by the classes which implement the interfaces.

Interfaces simply say 'Am a contract', which if you wish to use, should stick to some rules(give implementation to all abstract methods).

Multiple inheritance is omitted in Java by making sure that a class can extend only 1 class, in order to avoid the diamond problem. You can anyways have multiple inheritance of types in Java by using interfaces.

Anuj Balan
  • 7,629
  • 23
  • 58
  • 92
1

A Java interface contains a list of methods that must be implemented by the class that implements the interface. Thus, the methods have no body: the body of each method is in the implementing class(es).

Anderson Green
  • 30,230
  • 67
  • 195
  • 328
1

Simple Answer:

An interface provides a standard for implementation.

Explanation:
In Java an interface is similar to an abstract class in that its members are not implemented. For example,

public interface Comparable      
{   boolean less(Object m);
    boolean greater(Object m);
    boolean lessEqual(Object m);
    boolean greaterEqual(Object m);
}

An interface provides a standard for implementation.
Benefit of using interfaces is that they simulate multiple inheritance. All classes in Java must have exactly one base class, the only exception being java.lang.Object (the root class of the Java type system); multiple inheritance of classes is not allowed in java.

All instance methods are implicitly public and abstract. You can mark them as such, but are discouraged from doing so as the marking is considered obsolete practice. The interfaces themselves need not be public and several interfaces in the standard libraries are not public and thus used only internally.

An interface creates a protocol that classes may implement. Note that one can extend an interface (to get a new interface) just as you can extend a class. One can actually extend several interfaces. Interfaces thus enjoy the benefits of multiple inheritance. (Classes do not.) There are almost no disadvantages to multiple inheritance of interface (small name conflict problems are one exception). There are large disadvantages to multiple inheritance of implementation as in C++. These include efficiency considerations as well as the semantic difficulty of determining just what code will be executed in some circumstances.

The Polynomial class that implements Comparable will need to implement all of the functions declared in the interface.

public class Polynomial implements Comparable
{   . . .
    boolean less(Object m){ . . . }
    boolean greater(Object m){ . . . }
    boolean lessEqual(Object m){ . . . }
    boolean greaterEqual(Object m){ . . . }

    Polynomial multiply(Polynomial P){ . . . }
    . . .
}

A class may choose to implement any number of interfaces. A class that implements an interface must provide bodies for all methods of that interface. Also, We expect that an abstract class can choose to implement part of an interface leaving the rest for non-abstract subclasses.

The usefulness of interfaces goes far beyond simply publishing protocols for other programmers. Any function can have parameters that are of interface type. Any object from a class that implements the interface may be passed as an argument.

References:
Interface
Interfaces
Interface Wiki

Chandra Sekhar
  • 16,256
  • 10
  • 67
  • 90
  • 2
    -1; If you take text from a site then you should at least give a link to the original. Text ripped from this site: http://csis.pace.edu/~bergin/papers/Interface.html – maba Aug 31 '12 at 07:02
  • @maba, Sorry for your inconvenience, i just want explain the topic, i have taken from many places and edited it many times. if you really need to have links then this answer will be **full with links!** You need links or Good Answer? better you can concentrate to improve the answer, if you are able to do it. – Chandra Sekhar Aug 31 '12 at 07:31
  • We need good **original** answers. If whoever wrote the original wanted to come here and paste it in, more power to him. But you aren't him. You don't get to do that, without his permission. Simply providing a link to the original does not automatically absolve you of copyright infringement. But in this case, you didn't even do *that*. – cHao Oct 16 '12 at 12:54
0

Interface methods has no body like

public interface Flyable
{
public void fly();
}

because interface itself not going to do anything

interface is defines contract.

an interface, on other hand, defines what a class can do, not what it is. So interface is about verbs usually.

So the Flyable interface is doing nothing but defines the contract that the implanted FlyableObjects are going to fly.

like:

class Rocket implements  Flyable 
{
public void fly()
{
// do the stuffs.
}
}

interface

and ofcourse we can achieve multiple inheritance also only and only through interface.

subodh
  • 6,136
  • 12
  • 51
  • 73
0

if interfaces had bodies then it would have brought back the Deadly Daimond of Death problem.

Consider this example having interfaces with bodies

interface A {
    void print(){ System.out.print("A") }
}

interface B {
    void print(){ System.out.print("B") }
}

interface C extends A, B {
    // now since A and B have bodies interfaces would have had choice to not to override the default behavior
}

public class C_Implementer implements C{
    public static void main(String args[]){
        C c = new C_Implementer();
        c.print(); // gotcha!!!!! what should it print, A or B????
    }
}
Anshul
  • 159
  • 1
  • 10
0

You are asking "Why does Java not support multiple inheritance of implementation?"

This is discussed in the Java Tutorials, Multiple Inheritance of State, Implementation, and Type, but I wanted to give a specific example of the problems of multiple inheritance of implementation (as well as a new language feature solution at the end).

Imagine two interfaces (in our proposed version of Java that allows interface method bodies) that define a method with the same name.

public interface FaceOne {
    public void method() {
        System.out.println("FaceOne Version");
    }
}

public interface FaceTwo {
    public void method() {
        System.out.println("FaceTwo Version");
    }
}

And a class implements both interfaces, but doesn't override the method.

public class Inheriter implements FaceOne, FaceTwo {

}

When I call Inheriter.method(), which works since the class inherits the method from its ancestors, the problem arises: does the output print "FaceOne Version" or "FaceTwo Version"?

In addition, if the class were to override the method, but wanted to also call its ancestor's version using super, the compiler would again have trouble choosing between a version of the method.

This is why Java does not support multiple inheritance of implementation.


As an aside, I think an elegant way to implement this into the language would be as follows:

Continue to force implementing classes to override their ancestor interface's methods. This solves the first problem of a non-overridden method.

Then, use a similar notation as that of accessing an enclosing instance for an inner class to access a specific ancestor interface with super. The Inheriter class would then have multiple options:

  • Do not call super.method(), but rather only use newly-defined implementation.

  • Use FaceOne.super.method() to make the default inherited implementation output "FaceOne Version".

  • Use FaceTwo.super.method() to make the default inherited implementation output "FaceTwo Version".

  • Use a combination of the above:

One implementation could be:

@Override
public void method() {
    FaceOne.super.method();
    FaceTwo.super.method();
    System.out.println("Inheriter Version");
}

Outputting:

FaceOne Version

FaceTwo Version

Inheriter Version


Edit: According to this question this is apparently exactly how default implementations are structured in Java 8.

Community
  • 1
  • 1
snickers10m
  • 1,709
  • 12
  • 28