Interfaces instead of multiple inheritance?

I've read that "The Java programming language does not permit multiple inheritance , but interfaces provide an alternative."
But I also read contradictory information-There are no method bodies in an interface.
Java interfaces only contain empty methods? Apparently, if I want to share a method among classes, I have to re-write the methods in each class that implements the interface. That doesn't seem at all like multiple inheritance. Am I missing something?
It seems that I will have to cut and paste the implementation code from one class to another, and if I change the methods, I have to cut and paste it all over again.
I've read that interfaces save a lot of time re-writing methods, but how?
Does this really provide the same capabilities as multiple inheritance, or am I missing something?
Thanks,
Pat

Pat-2112 wrote:
I've read that "The Java programming language does not permit multiple inheritance , but interfaces provide an alternative."
But I also read contradictory information-There are no method bodies in an interface. That's not contradictory.
Inheritance is about type, which interfaces provide. It is NOT about sharing code, which is all that's lacking by not having multiple inheritance of implementation.
Java interfaces only contain empty methods? Apparently, if I want to share a method among classes, I have to re-write the methods in each class that implements the interface. That doesn't seem at all like multiple inheritance. Am I missing something? Yup. You're missing the point of inheritance, and the fact that delegation allows you to use an implementation defined in one class in another class.
It seems that I will have to cut and paste the implementation code from one class to another, Nope.
public interface Cowboy {
  void ride();
  void draw();
public interface Artist {
  void sculpt();
  void draw();
public interface CowboyArtist extends Cowboy, Artist {
public class CowboyImpl implements Cowboy {
  public void ride() {
   System.out.println("Giddyup!");
  public void draw() {
    S.o.p("Bang!");
public class ArtistImpl implements Artist {
  public void sculpt() {
    S.o.p("Demi Moore in Ghost. Yum!");
  public void draw() {
    S.o.p("Sketch a picture of a gun.");
public class CowboyArtistImpl implements CowboyArtist { // or implements Cowboy, Artist
  private final Cowboy cowboy = new CowboyImpl();
  private final Artist artist = new AristImpl();
  public void ride() {
    cowboy.ride();
  public void sculpt() {
    artist.sculpt();
  public void draw() { // uh-oh, what do we do here?
    artist.draw();
    cowboy.draw();
}The draw method is not relevant to this particular question. It's an example of one of the problems with MI, and I just included it since it usually comes up int these discussions anyway. Ride and sculpt demonstrate the point about delegation.

Similar Messages

  • Interfaces to replace multiple inheritence

    Howdy,
    I have, conceptually, the following situation: I have a Ball abstract class. The Ball has several
    concrete methods. It also has an abstract method getAppearance (that would somehow return how a
    Ball is visualized). I have several "adjective" subclasses that I would like to build from it, for example:
    SpikyBall, GlowingBall, ColorBall, etc. I would like these classes to be concrete.
    Additionally, I would like to have a concrete class of any permutation of this list of adjectives, for example:
    SpikyColorBall, GlowingColorBall, SpikyGlowingColorBall. I want to accomplish this
    using as little code rewriting as possible, and, hopefully, none at all.
    Using certain other single letter languages that I won't name here, I used Multiple Inheritence. A
    SpikyColorBall would inherit from both SpikyBall and ColorBall, who both inherited from
    Ball. I was told I could accomplish this in Java using interfaces instead of multiple inheritence, which
    Java doesn't support. How is this accomplished? Could you give me (or forward me to) a good
    example? Again, the power I'm looking for is multiple inheritence's code-reusability.
    As a side note, why did Java choose to use interfaces instead of multiple inheritence?

    Courtesy of yawmark...
    composition_v_inheritance
    Bruce Eckel, author of Thinking In Java, has this to say about composition vs. inheritance:
    When deciding between inheritance and composition, ask if you need to upcast to the base type. If not, prefer composition (member objects) to inheritance. This can eliminate the perceived need for multiple base types. If you inherit, users will think they are supposed to upcast.
    Choose composition first when creating new classes from existing classes. You should only used inheritance if it is required by your design. If you use inheritance where composition will work, your designs will become needlessly complicated.
    Bill Venners: Composition versus Inheritance
    Use inheritance (of implementation) only when the class satisfies the following criteria:
    1) "Is a special kind of," not "is a role played by a";
    2) Never needs to transmute to be an object in some other class;
    3) Extends rather than overrides or nullifies superclass;
    4) Does not subclass what is merely a utility class (useful functionality you'd like to reuse); and
    5) Within PD: expresses special kinds of roles, transactions, or things.
    -- from Java Design: Building Better Apps and Applets (2nd Edition), by Peter Coad and Mark Mayfield

  • Multiple inheritance in Java

    Why it is sometimes said that interfaces provide a form of multiple inheritance?
    Do you agree that interfaces can provide multiple inheritance? Explain.
    Some people say that Java does not support multiple inheritance, and others: a class can implement more than 1 interface. Isn't that multiple inheritance?
    Thanks

    >
    Some people say that Java does not support multiple
    inheritance, and others: a class can implement more
    than 1 interface. Isn't that multiple inheritance?Sort of, but you don't inherit any implementation from an interface.

  • How java support multiple inheritance by the use of interface.

    As per my understanding, Interface is just having the signatures of the methods not the implementation.
    So How java support multiple inheritance by the use of interface?
    Answer 1: we can institate interface reference by its implemented
    class.
              ����� interface inf...
              ����� class aa implements inf..
              ����� class bb implements inf....
               Now, inf i = new aa();
               inf i = new bb();
    Answer 2: We can extends as many interface as we want in the
    single
               interface.
               i.e. interface infFirst....
               interface infSecond....
               interface infThird....
               Now ,
               interface ingMulti extends infFrist, infThird...
    By above two answers its not prity clear as per the multiple inheritance in C or C++.
               i.e.
               class first{
               method abc();....}
               class second{
               method bbc()......}
               class multi::first::second{
               we can call to abc();.....as well as bbc();
    -Please give your important suggstion on the same.(Hope I explain it well.)
    -Jeff

    The keyword implement is used only for interfaces not
    for abstract class. If i am wrong correct me.I believe your right, but I will double check.
    As for the multiple inheritence think about the following code:
    class Animal {
        //  Animal generic stuff in this class
    interface Eat {
        //  Generic stuff that models eating behavior
    interface Runs {
        //  generic methods that model running behavior
    public class Horse extends Animal implements Eat, Runs {
        //  Stuff specific to a horse
    }The Animal class is generic but has stuff in it common to all animals.
    The Eat interface models behavior that is generic to eating, all living things have to eat something to survive. Herbavore are different from carnivores.
    The Runs interface models generic behavior to running, such as speed. A cheeta definately runs faster than a human.
    This brings us to the Horse class. It extends the Animal class because it "is-a" animal, and it implements the eat and runs interface because they are behaviors a horse has.
    I hope that helps.
    Extending an abstract class is the same as extending a regular class with the exception you MUST override all abstract methods in the abstract class. Thats not too difficult but I believe when designing classes, designing an abstract can be more diffecult than modeling the base class, and generic behaviors in interfaces. JMO.
    JJ

  • Multiple inheritance in tagging interface? Is it possible?

    I saw a code somewhere that goes like this:
    public interface Node extends Serializable, Clonable
    ...Is it possible? I know that Java doesn't allow multiple inheritance and that Serializable and Clonable are tagging interfaces where no method must be implemented by the programmer.

    KamenRiderZX wrote:
    I know that Java doesn't allow multiple inheritanceMore exactly: Java doesn't allow multiple inheritance of implementations. Inheriting multiple interfaces ("implements" for classes, "extends" for interfaces) is fine 'though.

  • No multiple inheritance in Java. Interfaces used.

    Hi,
    In java a class can extend only one class while the interface can extend any number of interfaces.
    Class extending only one class avoids multiple inheritance.
    Can you explain me the reason of avoiding this in classes and allowing interfaces to extend any number of interfaces ?

    Hi,
    In java a class can extend only one class while the
    interface can extend any number of interfaces.
    Class extending only one class avoids multiple
    inheritance.
    Can you explain me the reason of avoiding this in
    classes and allowing interfaces to extend any number
    of interfaces ?The real question is: do you have a need for multiple inheritance?
    If so, I would be glad to hear about this concrete problem.

  • Multiple Inheritance problem persists in Interfaces

    Hi,
    I tentatively made a program and found that multiple inheritance problem of C++ persists even with interfaces. Although this is definetely a special case but I want to know what is this problem known as( i know that this is perhaps known as diamond problem in C++). And is there a way out of this thing.
    interface one
         int i=10;
    interface two
         int i=20;
    interface z extends one,two
    public class xyz implements z
         public static void main(String [] a)
         System.out.println(i);
    }O/P
    D:\Education\Java\JavaStudyRoom\Applets>javac xyz.java
    xyz.java:16: reference to i is ambiguous, both variable i in one and variable i
    in two match
    System.out.println(i);
    *^*
    *1 error*
    Thanks for replying

    suvojit168 wrote:
    I tentatively made a program and found that multiple inheritance problem of C++ persists even with interfaces. Although this is definetely a special case but I want to know what is this problem known as( i know that this is perhaps known as diamond problem in C++). And is there a way out of this thing. This is not the so called diamond inheritance problem. What you have here is an ordinary name clash. And as has been noted you can resolve it by qualifying which constant you're referring to, like
    System.out.println(one.i);
    For the diamond inheritance problem to apply both the one and the two interfaces would need to inherit a common ancestor (that's how the diamond is formed). Furthermore the common anscestor would need to carry implementation which would then be inherited two ways, once via one and once via two. This is the diamond inheritance problem Java is avoiding by allowing single inheritance of implementation only.
    P.S. My previous post was posted my mistake.

  • How too ? Multiple inheritance with Interface ?

    I understand that Java does NOT allow Multiple inheritance. I've read many posts trying to understand the interface statement.
    I understand that an interface implements a behavior! But can someone please explain how I would inherit Multiple classes (Thread and JPanel) using an interface ?
    Many Thanks,
    Rob

    I understand that an interface implements a behavior!No, it doesn't. It merely defines what methods must be present in a type. A class is what actually implements the behavior for a particular implementation of that type.
    But can someone please explain how I would inherit
    Multiple classes (Thread and JPanel) using an
    interface ?You can't. Thread and JPanel are classes. A given class can only extend one class.
    A class can implement multiple interfaces however. So if at least one of Thread or JPanel were an interface, then your class could inherit from both of them. But that's not the case, so you can't.

  • How does Java achieve multiple inheritance using interfaces

    Java does not allow multiple inheritance through classes as classes might contain methods with same names. what happens if a class implements two interfaces with same method names?
    I am really confused abt this? Can anybody help me out?
    Message was edited by:
    vijkris

    yes to avoid the ambiguous functions which can result due to multiple inheritance of classes like in c++ , java doesn't have this through classes. But if you have same method (both return type and parameter) then java doesn't bother and it won't complain as ultimately only one implementation is possible in deriving class even though method declalaration is there in both the interfaces. If return type changes then it won't compile as it can't overide the both methods as they have same name and different return types. thats why inside interfaces they restricted the implementation of methods so that it can work fine in ambiguous scenarios.

  • Multiple Inheritance

    Hello,
    I have been programming Java for last year,
    evolved in quite some skills with it, and
    really think it is great...
    However, I was shocked to find out that there
    is no multiple inheritance feature.
    I know it is rare, and my case proves it
    (1 year now, I never needed it)
    HOWEVER, when one needs multiple inheritance,
    then they really do need it.
    I have interfaces which I would like implemented
    in their respective class (ie ISomething be
    implemented in CSomething), then some classes
    I need to implement many of those interfaces...
    Now I am forced to have those classes extend
    multiple interfaces, and duplicate the interface
    implementation code inside each of them.
    I dont mind a little bit of copy/paste, nor
    do I care about the compiled classes being
    slightly bigger, BUT the problem is that
    when I need to change some behaviour in those
    interfaces, in the near (or far) future, I will
    have their implementation scattered in many
    classes... This is dangerously error prone and
    not proffesional at all... And I do not think
    that including multiple inheritance in the language
    could be more error prone than this...
    I think the Java team does a 100% perfect brilliant
    job, but at this specific point, they "over-tried"
    to "protect" the programmers from themselves...
    Well, thats all,
    I think some next version of Java should support
    multiple inheritance. And the Java "warning" could be :
    "if you havent missed it till now, then you probably
    do not need anyway, so do not bother using it just
    because it exists"
    Thanks for reading my thoughts,
    Dimitris

    Personally I never need multiple inheritance of code and I try to avoid inheritance of code whenever possible. A common mistake in OO is too use inheritance as a way of reusing code. Code reuse is much easier, cleaner and more powerful by using composition instead. Only use inheritance for polymorhism (to use multiple implementations for the same interface). An example:
    interface A {
      void ma();
      void maa();
    interface B {
      void mb();
    class C implements A, B {
      private A a;
      private A c;
      private B b;
      public void ma() {
        a.ma();
      public void maa() {
        c.maa();
      public void mb() {
        b.mb();
    }This is much more powerful than code reuse through inheritance. In this example I use one method from 'a' and one method from 'c' when I implement interface A. I can change the value of 'a', 'b' and 'c' during runtime, and I dont have to reuse all the code in 'a' and 'b', I can select which code to reuse. This is the power of composition and interfaces. Note that I only access 'a', 'b' and 'c' through the interfaces A and B, never directly through their implementations.
    I would recommend you to look at your design and start to think about interfaces and inheritance, not about code reuse though inheritance.

  • Is there (REAL) multiple inheritance ?

    Hi brothers,
    how r u..
    let us discuss about one property of java, what do you think ..
    The ability of multiple inheritance is one famous property of java, and that is done by interface, but I think that is not multiple inheritance really in contrast with C++ especially about inheriting of methods.
    If a class M implements interface I and class C, M or its subclasses must implement all methods of I, i.e., the bodies of those methods are made in in M class; then where is the multiple inheritance or even the linear inheritance?
    Is the multiple inheritance for methods prototypes only?
    I[b] suggest that you put those methods in M class directly instead than putting them indirectly.
    C++ provides real multiple inhritance for all members.
    May be if the interface contains constants, we can see multiple inheritance clearly, OR :
    in use APIs, but I dont have much experince in APIs?
    What do you think in what I said?

    Hi brothers,Hi :)
    how r u..fine thanks, and you?
    let us discuss about one property of java, what do
    you think ..I'll do my best :$
    If a class M implements interface I and class C, M or
    its subclasses must implement all methods of I, i.e.,
    the bodies of those methods are made in in M class;
    then where is the multiple inheritance or even the
    linear inheritance?
    Is the multiple inheritance for methods prototypes
    only?Inheritance is there to make your code more understandable I guess.
    An Interface is there to define what the object is about. Persoanally I always felt that true inheritance in java is done when using the 'extends' word rather then the 'implements' keyword. When extending a class you no longer have to declare that method in your class or subclass (unless it is an abstract class).
    I am not a genious in Java, however I always felt that an interface is there to specify the type of the object.
    I suggest that you put those methods in M class
    directly instead than putting them indirectly.But then your set of classes would not longer be understandable, and your objects can no longer have logical meaning. For example imagine haveing an class called 'John' I would never want to have all the methods and properties that describe 'John' to be lofically named only in 'John'! I would want an interface that describes to me that John needs to have two legs and two arms. An other interface that describes to me that John can walk, run, sit, etc, and another interface that tells me that John has a name, surname, id number and so on.
    C++ provides real multiple inhritance for all
    members.Then I guess C++ is the language for you ;)
    May be if the interface contains constants, we can
    see multiple inheritance clearly, OR :An interface can contain constants as much as I know!
    What do you think in what I said?was gona ask the same thing, but now I am afraid I wrote a bunch of sh*t :$ :(

  • More about multiple inheritance

    OK, you can solve problems where multiple inheritance is needed by using interfaces. But im facing a problem where it cant help me. Im constructing a system where there are componentes that need to extend JTextField as well Observable. I dont have interfaces above it in the hierarchy to substitute multiple inheritance. What can I do?
    When you have a scenario that you have to use two (or more) third party classes, and need to inherit from both, how do interfaces can help? If ate least I had multiple inheritance from classes...

    << Begin Rant >>
    I have seen more inherited code that is terribly designed because multiple inheritence was available.
    The example provided is a perfect example of this: At first blush, it seems easy to combine the UI and data components by combining Observable and JTextArea. If you were able to do this, the person inheriting your code in 3 years will curse your name.
    Nothing pisses me off more (well, I'm sure there are other things, but...) than attempting to debug C++ source code and finding that function calls are being made to multiple super classes.
    Here's a fun one: try adding an innocuous method getInfo() to a class you've inherited, only to find that someone uses getInfo() in one of the super-classes, and it has been declared as 'friend' because the design is piss poor and it was the only way they could make the function available. Now, I have to go on a goose chase searching for all the places in the entire type hierarchy that getInfo() is used and change the code to explicitly call the other base class.
    It gets to the point where its easier to name it getInfo2() (like that's good design) and get on with things.
    MI is evil, evil, evil in any environment where you are trying to have code re-use and multiple teams.
    I find that most programmers who insist that multiple inheritence is a good thing just don't know how to use the Composite design pattern.
    Sun's decision to not support MI in Java is a sound one: the result is code that can be easily read and understood.
    << End Rant >>
    Whew... I feel much better having said that...
    - K

  • Problems of no multiple inheritance.

    I have created two classes RECTANGLE with attributes Length and Height and PLANERECTANGLE, with various attributes required to specify the rectangle's center, an attribute that can be checked to see if it is inside an instance of rectangele. However, i am finding this following requirement difficult to understand.
         In Question 5, we specified PlaneRectangle as a subclass of Rectangle. Suppose that we wanted the following generic behaviour to be implemented in a number of different �kinds of� shapes: being able to move a shape, check if a point is inside a shape, and check if another shape lies completely inside a specified instance of some shape. Java will not let us do this using multiple inheritance. How else could we specify this? Rewrite the Java code to illustrate use of this different method.
    Thanks - Mark Costello.

    The answer would be an interface
    public interface Shape
    public void moveShape();
    public boolean containsPoint(int x, int y);
    public boolean containsShape(Shape s);
    Every shape class would then implement this interface:
    public class Circle implements Shape
    ... and would need to implement those methods that
    were specified (but not implemented) in the interface.

  • Alternative for multiple inheritance (AbstractQueue and AbstractList)

    Hello all,
    What is the best alternative for multiple inheritance? I want to make a list, which supports queue operations. Both AbstractQueue en AbstractList are useful, so I would like to use them both, instead of implementing the methods myself or copying the code.
    thanks

    Do you mean you want a class just like LinkedList?
    Why don't you look at the code for LinkedList. Perhaps you could even use it.
    Most Queue methods have trivial implmentations using a List.
    From the source for LinkedList
    public class LinkedList<E>
        extends AbstractSequentialList<E>
        implements List<E>, Queue<E>, Cloneable, java.io.Serializable

  • Question about multiple inheritance

    Why does java not support multiple inheritance, but also give you the ability to use interfaces?
    I've done a quick search on here which turned up the same thing as the books on java I've read - they tell me that java doesn't support multiple inheritance, and that it supports interfaces, but not why.
    And from what I can see, the between multiple inheritance and single inheritance + interfaces make them seem almost equivalent, especially when you consider abstract classes. So why did the java designers make this decision?
    Edit: Just to say I've never programmed in an OO language that supports multiple inheritance, so I've never had to deal with it. Also, single inheritance has never crippled any of my designs (not that there have been that many), I'm not whingeing, just asking.
    Message was edited by:
    Dross

    Why does java not support multiple
    inheritance, but also give you the ability to use
    interfaces?It does support MI, just not MI of Implementation.
    why.
    class Beasty { }
    class Horse extend Beasty {
       public void gallop() { System.out.println( "horse" ); }
    class Donkey extend Beasty  {
       public void gallop() { System.out.println( "donkey" ); }
    class Mule extend House, Donkey {
    Mule mule = new Mule();
    mule.gallop();what would this print out.
    MI of implementation makes life harder, but adds very little to the party. So why add it?

Maybe you are looking for