Multiple inheritance, delegation and syntactic sugar

Given that delegation of an interface to a class member gives you most of the effect of multiple inheritance, why isn't there any syntactic sugar in the language to make this easy?
For example, you could have:
class B extends A implements I delegate i { I i = new IAdapter(); }
The semantics is simple: for each method in each delegated interface, if there is no method with that signature defined in the class then create one with a body that delegates the call to the given member. If there is an ambiguity from multiple interfaces, just flag it at compile time so that the programmer must add an explicit method.
This doesn't impact the class file format as it isn't doing anything that can't be done longhand in the code. It would even provide some protection from interface changes, as a recompile would pass the problem on to the delegate (which would likely inherit from some standard adapter class which would be modified at the same time as the interface).
Why isn't this done (apart from because MI is inherently evil and just suggesting this addition means I'm a bad person). It would make the language a tiny bit bigger, but at least when people ask why Java doesn't have proper MI you could answer 'it does and you do it like this' with an almost straight face.
Jonty

The only problem with this is that with multiple
delegates it kinda falls apart.
When yourFunc() is called on an instance of A, which
function is called?original> If there is an ambiguity from multiple interfaces, just flag it at compile
original> time so that the programmer must add an explicit method.
My suggestion was that if there is any ambiguity then no delegation is made, forcing the programmer to do it manually.
Normally in Java it's no big deal when multiple
interfaces have the same methods in them.Actually, I find it a bit of an odd choice by the language designers allowing same signature functions defined in different interfaces to not generate a name clash. Normally this indicates that there is, or soon will be, a bug. I can't think of any situation where this is good programming - if you want the method to exist in both interfaces then it should be defined in a third and inherited into both. This makes it clear that it really is the same method.
Not saying that delegates are a bad idea, but simple
examples don't prove that delegates are a worthwhile
feature to add.The point is that delegation is a commonly used pattern, and is almost always trotted out as a good way of getting most of multiple inheritance. The comments so far are about the problems with this pattern, not with my suggestion to make it easier to use.

Similar Messages

  • Enumerate multiple inheritance scenarios and their java equivalents?

    hi,
    ppl have often said things like
    "java doesn't support multiple inheritance but this is ok, since there are other mechanisms for doing the same thing (by which we nearly always mean interfaces)"
    how solid a statement is this? are there any formal methods available eg smt like "over all possible inheritance trees over all possible classes, only a handful of cases are distinct when viewed from the converting-to-single-inheritance scheme"?
    the two things mentioned as harder to workaround are mixins and the diamond problem - are there more?
    also what other mechanism apart from interfaces (if any) are useful?
    any help appreciated,
    asjf

    What I say is that it doesn't matter since there is
    almost never any need for MI. Most of the time it is
    used it is used because the developer/designer did not
    understand what they were doing and it should not have
    been used in the first place.
    That leaves one with very few cases where it should
    ever be used. And that coupled with the fact that a
    developer should never use it unless they are very
    experienced (so that they actually know that it should
    be used,) means that practicing programmers should
    leave discussion of such usages to scholarly
    journals.thanks :) I guess my problem is that often with computer stuff you don't have to rely on other peoples experience about things - you can go and test it yourself
    I've done very little C++ development, and so have never come across real-world multiple inheritance. I bumped into the first situation with some java code where it might've been a neat solution recently but this could easily fit into the "designer did not understand what they were doing" category from above..
    will have a casual look around the scholarly journals if I can find any that look promising :)
    asjf

  • 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

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

  • Multiple inheritance and super

    How to I get to a super function when using multiple inheritance? For example, the code below doesn't compile if Human extends Job, but works fine if Human only extends Animal.
    package test;
    import java.lang.System;
    public class Job {
    public class Animal {
    public attribute isStanding:Boolean = false;
    public function printStatus():Void {
    System.out.println( if (isStanding) "Standing up" else "Laying down");
    public class Human extends Animal, Job {
    public attribute isAtWork:Boolean = false;
    public function printStatus():Void {
    System.out.println( if (isAtWork) "At the office" else "At home");
    super.printStatus();
    var person:Human = Human{};
    person.printStatus();

    Thanks! Works great. I never even tried that since my brain is wired to only use that syntax for calling a static method/function/field.
    Note: If you change the class definition in the original sample from
    public class Human extends Animal, Job {topublic class Human extends Animal {The original compiles and runs as you'd expect. So the 'super' keyword exists in some form and has the expected result for singular inheritance when used to call parent methods. I think you are thinking of using it to call constructors. In that usage I think you are right that it doesn't work at all in JavaFX.

  • What is single inheritance, multiple inheritance, and describe Java's notio

    What is single inheritance, multiple inheritance, and describe Java's notion of an interface?
    Can you give me example or reference link? thx

    Single inheritance is getting features like data and methods (functions) from a so called parent class. multiple inheritance is the same but you derive features from multiple parent classes (not supported by java). Interfaces are a way around this because you can inherit multiple interfaces. Inheriting from interfaces is like a promise to implement certain methods that these interfaces define but doesn't implement themselves.
    check around java.sun.com in the tutorials section, you can probably find a text that describes object oriented program and how it is implemented in java.

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

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

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

  • 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?

  • INF Looking for means to dialog C#-Dev team about multiple inheritance.

    Please help.
    I really need multiple inheritance with C#. Is there any forum/means to have a dialog with the dev's for C# about this? The amount of extra work and maintenance costs of not having multiple inheritance has been a big problem, but lately, it has really become
    a burden for not having. The maintainability and reuse-ability of code is drastically reduced without it.

    Btw, I think that this has been discussed
    many times before. Almost once or twice each year since .NET is released (that's 12 years by now).
    I don't think you can make them allow this feature as tons of example trying to convince them this is needed has been proved not necessary to use multiple inheritance by them.
    Many of the discussions ends with something like "Java also does not support multiple inheritance but there isn't seems to be a problem for them". Maybe you can get more luck to convince Oracle to include MI in Java first.
    Btw, I found it hard to believe you need Multiple Implementation Inheritance to... improve maintainability of code? WTF??? I think Multiple Implementation Inheritance has it own place in the hall of fame for the bugs it caused in languages that supports
    it, even in C++.

  • Alternatives to multiple inheritance for my architecture (NPCs in a Realtime Strategy game)?

    Coding isn't that hard actually. The hard part is to write code that makes sense, is readable and understandable. So I want to get a better developer and create some solid architecture.
    So I want to do create an architecture for NPCs in a video-game. It is a Realtime
    Strategy game like Starcraft, Age of Empires, Command & Conquers, etc etc.. So I'll have different kinds of NPCs. A NPC can have one to many abilities (methods) of these: Build(), Farm() and Attack().
    Examples:
    Worker can Build() and Farm()
    Warrior can Attack()
    Citizen can Build(), Farm() and Attack()
    Fisherman can Farm() and Attack()
    I hope everything is clear so far.
    So now I do have my NPC Types and their abilities. But lets come to the technical / programmatical aspect.
    What would be a good programmatic architecture for my different kinds of NPCs?
    Okay I could have a base class. Actually I think this is a good way to stick with the DRY principle.
    So I can have methods like WalkTo(x,y) in
    my base class since every NPC will be able to move. But now lets come to the real problem. Where do I implement my abilities? (remember: Build(), Farm() and Attack())
    Since the abilities will consists of the same logic it would be annoying / break DRY principle to implement them for each NPC (Worker,Warrior, ..).
    Okay I could implement the abilities within the base class. This would require some kind of logic that verifies if a NPC can use ability X. IsBuilder, CanBuild,
    .. I think it is clear what I want to express.
    But I don't feel very well with this idea. This sounds like a bloated base class with too much functionality.
    I do use C# as programming language. So multiple inheritance isn't an opinion here. Means: Having extra base classes like Fisherman
    : Farmer, Attacker won't work.

    Hi
    PandoraElite,
    You can inherit from multiple interfaces (and use explicit interface implementation), but not from classes in C#. You can almost simulate it:
    In C# we don't support multiple inheritance
    http://blogs.msdn.com/b/csharpfaq/archive/2004/03/07/why-doesn-t-c-support-multiple-inheritance.aspx
    What would be a good programmatic architecture for my different kinds of NPCs?
    In your scenario, we can define some interface ,An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified
    in the interface definition.
    How to use? Please refer to the following article.
    http://www.codeproject.com/Articles/18743/Interfaces-in-C-For-Beginners
    Best of luck!
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

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

Maybe you are looking for

  • Error in Creation of a New View Object from Existing Entites

    I define a Complex JOIN in the expert mode of the View Object Creation Mode. On trying to access the VO, the system returns an error, unable to creat View Objecy. THe SQL Statement begins with SELECT * from ( select ...My actual Query) Is it possible

  • Regarding Cheque bouncing

    Dear All My client is asking that  after posting the cheque for Depositing  .....some days the particular BP cheque has Bounced  in this case he wants to track that Particular cheques which has bounced......Once if it has bounced   he wants to cancel

  • Ipod does not appear in the organizer.

    Hi All. I've installed the SDK 8 on my Mac OS x 10.5. While following the Apple "How to start" I'v tried to get my Ipod device info from the xcode organizer. Unfortunately my Ipod does not appear in there and it does being recognized by the Itunes 7.

  • Online pdf - changing who the doc is submitted to

    I am creating a pdf form that people can complete online. Got that figured out, but, I need to change who the document is submitted to.  It seems to pull up the email of the previous person who used this computer and that email is no good any more. 

  • Despooler.Box Receive Folder Filling Up Space

    I have one primary site and 5 secondary sites and with a few of the secondary sites we store all the files on the D:\ drive and the drive is filling up quickly then releasing space again.  I've done a tree size and it seems to be the Despooler.Box\Re