2

Guys before you start down voting me please read this question and please understand that I do not try to start anything unpleasant here.

The only reason for this question is that I'm becoming more and more aware of that in order to be more employable I have to know either Java and/or C#.

Ok here is the question:

I know that multiple inheritance is forbidden in J and C#. But if I do something like this (because I would like to have a class which inherits from two classes B and A):

//code in Java
public class B
{
    public void methodFromB()
    {
    }
}

public class A extends B
{
    public void  methodFromA()
    {
    }
}

public class C extends A
{
    public void methodFromC()
    {
    }
}

So in fact as far as I understand this, I do inherit from both of them (A and B and yes I do understand that formal explanation for this is that the object A is a specialized B but none the less if I want to do it I will but it just doesn't look pretty)

But instead of doing this in one declaration I have to first create one class inherit from another class and then derive from it?

Funny thing though. Having declared those classes as above (in NetBeans) I see that after creating an instance of class C (in main) I cannot invoke methodFromC on it which is the method defined in this class.

What is the reason for that?

Thanks.

There is nothing we can do
  • 23,727
  • 30
  • 106
  • 194
  • 1
    Could you post a sample of the code that you're trying to make work in "Having declared those classes as above (in NetBeans) I see that after creating object of class C (in main) I cannot invoke methodFromC"? – Bruno Aug 12 '10 at 10:45
  • 11
    This is not an example of multiple inheritance, it's merely ordinary inheritance as the gods meant it. The multiple inheritance which java voids is where you have classes Ba and Bb who both implement A, and then class C which implements both Ba and Bb, resulting in a diamond shaped structure. Confusion sets in when Ba and Bb both override a public method m(), which C then calls. Since it's never defined which implementation of m() which is being called, results can be unexpected. This is why the design choice was made to only allow implementation of a single type. – mikek Aug 12 '10 at 10:49
  • I wouldn't say that this is *forbidden* in Java and C#, it is simply not implemented in those languages (for the reasons that mikek states) – Kris Aug 12 '10 at 11:03
  • 3
    @mikek I'm sorry but I cannot agree with you in one aspect. God meant for child to be a subclass from TWO parents, I hope you agree on that. – There is nothing we can do Aug 12 '10 at 11:07
  • 2
    @A-ha, The child/parent analogy is quite bad when talking about inheritance. If A extends B, then an A object *is a* B object. You wouldn't say that a son *is* his father/mother. – aioobe Aug 12 '10 at 11:13
  • @aioobe completely dissagree. And you also do not say that child is only his mother or only his father do you? But you do say (when talking about multiple inheritance) that class A has common things with class B and class C, would you agree? – There is nothing we can do Aug 12 '10 at 11:17
  • @aioobe: agreed. OOP inheritance is not analogous to biological inheritance - I wished they'd used some other word. – MusiGenesis Aug 12 '10 at 11:20
  • @MusiGenesis Again, I have to completely dissagree with you. As a matter of fact the way it (inheritance) is explained in books etc is as a parent child relation. – There is nothing we can do Aug 12 '10 at 11:23
  • @A-ha: Please tell me that you're kidding? – mikek Aug 12 '10 at 11:27
  • @mikek No I don't. Didn't you never came across fraze like class A is a parent to class B or class B is a child of class A? That is the way how inheritance is very often reffered to isn't it? – There is nothing we can do Aug 12 '10 at 11:29
  • @A-ha: Please leave out the references to God if you want to be taken seriously. The entire world doesn't share your values, so trying to relate something in a way that they wouldn't understand just hurts your chances of receiving a valid answer that doesn't lambast your personal beliefs. Thanks. – Bob G Aug 12 '10 at 11:31
  • @mikek this " It is entirely possible to derive a class whose object will behave incorrectly when used in a context where the parent class is expected" is from here http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) – There is nothing we can do Aug 12 '10 at 11:31
  • @DarkBobG if you would read this thread carefully you would realize that it wasn't me who mentioned God in here (from lower case letter by the way). – There is nothing we can do Aug 12 '10 at 11:33
  • @A-ha: yes, that is how class inheritance is *sometimes* described. That does not mean it's a good or accurate description. – MusiGenesis Aug 12 '10 at 11:33
  • @DarkBobG: `mikek` started the "gods" reference in his first comment - `A-ha` was just responding to that humorously. – MusiGenesis Aug 12 '10 at 11:34
  • @MusiGenesis but would you agree that forbidding multiple inheritance is for the reasons that it is hard to "maintain" not because is illogical and doesn't reflect the world in which we live in? – There is nothing we can do Aug 12 '10 at 11:36
  • @A-ha: If you read just a little bit of type-theory, you'll come to realize that a type can be seen as the set of all objects with that type. When you've realized this, you'll also realize that a sub-type of a type actually corresponds to a *subset* of that type. Draw this on a paper, and you'll realize that it's not anything like a parent-child relationship. (Is the set of children a subset of the set of parents??) – aioobe Aug 12 '10 at 11:36
  • @Ah-a: The gods I was referring to were naturally James Gosling et. al, who else? :P – mikek Aug 12 '10 at 11:38
  • 1
    gods vs: God. He was talking in general sense, you were declaring a specific. I didn't mean to offend, just relating from personal experience that introducing religion, even in a general sense, always throws conversations like this into a negative light. No harm intended. – Bob G Aug 12 '10 at 11:41
  • @aioobe and why doesn't this have nothing to do with parent-child relationship? Can't agree with you on that one. – There is nothing we can do Aug 12 '10 at 11:42
  • @A-ha: I don't think class inheritance (either single or multiple) reflects the physical world in which we live. Class inheritance is actually just a useful (if potentially dangerous) byproduct of the way computers work interally. – MusiGenesis Aug 12 '10 at 11:42
  • If class inheritance worked like biological inheritance, then I would literally be both Mom and Dad *and* Myself. I would be able to present myself (i.e. do everything they do and look the way they do) to the world as either Mom, Dad or Myself. My children would be themselves, me, my wife, Mom or Dad, my wife's Mom or Dad, and so on. – MusiGenesis Aug 12 '10 at 11:45
  • @DarkBobG what do you mean "He was talking in general sense, you were declaring a specific" how more specific was I then he was? Could you elaborate on this one? – There is nothing we can do Aug 12 '10 at 11:46
  • @MusiGenesis: Well, not really. OO-design is just one of many paradigms which we as humans use to organize our instructions to the processor. It all translates into the same sequential machine code in the end. – mikek Aug 12 '10 at 11:47
  • @MusiGenesis but that exactly how it is. Sometimes you (one) describes (introduce) himself as a parent of someone, sometimes as a child of someone and sometimes as a employee of someone. Isn't that how things works in this world? – There is nothing we can do Aug 12 '10 at 11:48
  • @A-ha: Do I really need to explain the difference between a lower case plural "gods" vs: the word "God" with an uppercase G? If so, then I apologize, but I'll have to decline. This is neither the site, nor the time or place for such a discussion. Back to why this is NOT multiple inheritance! – Bob G Aug 12 '10 at 11:48
  • @MusiGenesis and are paradigms of OOP to be able to model are classes so they reflect some aspect of world around us as exactly as possible? – There is nothing we can do Aug 12 '10 at 11:50
  • @mikek: I mis-characterized inheritance when I called it a "byproduct of the way computers work internally." You are correct that it's a way of organizing processor instructions, one that takes powerful advantage of the way computers work internally. – MusiGenesis Aug 12 '10 at 11:53
  • 1
    A-ha: The reason that the parent-child analogy is a poor one is because the parent and child may be one and the same person. I as an instance of MikeK implements the class HumanBeing which implements the class Mammal which implements the class VertebraeAnimals which implements the class AnimateObject. I am all of those at the same time, depending on level of abstraction. The reason that multiple inheritance isn't allowed in Java is the confusion that would arise of I happened to implement Mammal and Bird at the same time. – mikek Aug 12 '10 at 11:53
  • @A-ha: no, there is no particular reason that any programming construct *has* to model the physical world exactly. Code inheritance is useful all on its own. – MusiGenesis Aug 12 '10 at 11:55
  • @DarkBobG no you don't have to explain. But I would be happy if you could explain which gods intended for a child to have just one parent. – There is nothing we can do Aug 12 '10 at 11:56
  • @mikek again situation from our world - a bat. – There is nothing we can do Aug 12 '10 at 11:58
  • @All ok guys I have to finish now (will come back here later.) Thank you for your answers. – There is nothing we can do Aug 12 '10 at 11:59
  • A-ha: Nope, a bat is a mammal who just happens to fly. It doesn't lay eggs, doesn't have a beak, and is not related to any other birds. And what god intended a child to have only one parent? James Gosling, of course. – mikek Aug 12 '10 at 12:01
  • @A-ha: whatever god bacteria worship probably intended for a child to have just one parent. – MusiGenesis Aug 12 '10 at 12:02
  • 1
    @A-ha: http://en.wikipedia.org/wiki/Asexual_reproduction – Bob G Aug 12 '10 at 12:12
  • @DarkBobG I didn't say that it isn't possible I've just stated that multiple inheritance is more natural and more wildly spread and used than single inheritance. That's why you have to provide link to something which is not so popular because most people are not familiar with this. And if we have to follow this road: why do you think asexual (single inheritance) reproduction is used only by the lowest forms and more sophisticated forms are using "sexual reproduction" (multiple inheritance)? – There is nothing we can do Aug 12 '10 at 12:21
  • @mikek and what about mamals who lay eggs? Don't they share some of the properties with birds? But it really doesn't matter. I understand multiple inheritance as something more natural and you don't. And that's ok with me. And the explanation that multiple inheritance may be misused? Well you can misused single inheritance if you aren't correctly educated (I'm not saying that you're not I'm just giving an example) by inheriting wheel from a car. I suppose the conclusion here will be that for some people multiple inheritance is the more natural way and for some it isn't. – There is nothing we can do Aug 12 '10 at 12:23
  • @A-ha: You asked for an example. Whether or not it's possible, doesn't mean that it's the best solution for an approach. I'd daresay that the bacteria are far more versatile than we are with their single inheritance, given that their structures are capable of existing outside of nominal conditions, whereas humans are so fragile, that we move outside of our range of operating norms, and we die. Multiple inheritance, like humans, is a fad. – Bob G Aug 12 '10 at 12:28
  • 1
    A-ha: Mammals that lay eggs? They implement the class Monotreme, while we as placental mammals implement the class Eutheria (isn't Wikipedia great?). But seriously, you are in some way aware of the fact that Object Orientation is an entirely human construct, and in no way relates to the natural world? You can write three different programs in Smalltalk (OO), Basic (imperative) or Haskell (functional) and they may compile to the exact same machine code. OO is just a comfortable way for us as programmers to organize our programs. – mikek Aug 12 '10 at 12:32
  • @mikek "and in no way relates to the natural world"? I'm sorry mikek but that's just not true. – There is nothing we can do Aug 12 '10 at 12:41
  • @A-ha: Really? Care to back that up, or at the very least try to refute my statements? – mikek Aug 12 '10 at 14:52
  • @mikek here http://stackoverflow.com/questions/3470025/is-object-oriented-programming-in-any-way-related-to-the-natural-world-closed I've asked this question and two answers I've got before it was closed clearly suggest that it is not true that object oriented programming isn't in any way related to the natural world. – There is nothing we can do Aug 12 '10 at 17:05

5 Answers5

7

Even though you are creating an instance of C, whether C's methods are visible depends upon the compile-time type that you are using. For example,

C c = new C();
c.methodFromC();  // fine

Is valid, but

A a = new C();
a.methodFromC();  // compiler error

is not, since the compile time type is an A, which does not have methodFromC declared.

Note that since both C and A are subclasses of B, calling methodFromB would be fine in both cases.

mdma
  • 56,943
  • 12
  • 94
  • 128
  • but in NetBeans I cannot (it does not shows that it's available) c.methodFromC(); Why? – There is nothing we can do Aug 12 '10 at 11:09
  • 2
    With the code you have now posted, I don't see why there is a problem. Have you tried actually typing in the method to see if the code compiles? Auto-complete and compiling are not always the same thing! Otherwise, double check access modifiers (make everything public) and double check you are using a lowercase c, i.e. `c.methodOnC()`. If the C. is uppercase t will not work, since that would imply a static method. – mdma Aug 12 '10 at 11:18
  • yes, it does compile even though it says that it cannot find the symbol. Thanks. – There is nothing we can do Aug 12 '10 at 11:25
6

I agree with mdma. Also note that this is NOT multiple inheritance, this is chained inheritance. Multiple inheritance is when a class inherits from more than one class at the same time:

class A {}
class B {}

class C extends A, B {}

Which is forbidden if you're not coding in C++

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
vulkanino
  • 9,074
  • 7
  • 44
  • 71
2

That is not multiple inheritance. And you are right C# does not support true multiple inheritance. For what it is worth the canonical pattern for simulating multiple inheritance in C# is below.

public interface IA
{
  void DoA();
}

public interface IB
{
  void DoB();
}

public class A : IA
{
  public void DoA() { Console.WriteLine("A"); }
}

public class B : IB
{
  public void DoB() { Console.WriteLine("B"); }
}

public class MultipleInheritanceExample : IA, IB
{
  private IA m_A = new A();
  private IB m_B = new B();

  public void DoA() { m_A.DoA(); }
  public void DoB() { m_B.DoB(); }

}

It is definitely not as elegant as pure mulitple inheritance, but gets the job done, albiet with more work. You get most of the benefits of multiple inheritance including the most important one, polymorphism. However, you do not inherit the implementation. You have to reimplement all members inherited from all base classes. This is done by mapping those member calls onto concrete instances of each base class.

In C# you can take advantage of extension methods to mitigate the problem of not inheriting the implementation.

public static class IAExtensions
{
  public static void Foo(this IA target)
  {
    target.DoA();
  }
} 

This, of course, has its own problems. It is not actually causing any kind of inheritance which means the IA interface does not actually have the Foo method. That means only the code which imports the IAExtensions class can use methods from it. In other words, there is no polymorphism here.

You can use of these mechanisms together to cludge together something, that for the most part, resembles and functions like multiple inheritance, but it is not as elegant. Personally, I find the workarounds that C# developers are adopting to mimic mulitple inheritance more offensive than if pure multiple inheritance were used. But, it is unlikely that C# will get mulitple inheritance any time soon or perhaps ever.

Brian Gideon
  • 47,849
  • 13
  • 107
  • 150
1

An alternative in C# (and may exist in Java, but I'm not a Java person so I don't know) is interfaces.

public interface C
{
    int SomeMethodInC();
}

public class A
{
}

public class B : A, C
{
}

... in other class....
B someB = new B();
i someInt = someB.SomeMethodInC();

It looks like multiple inheritance, but it isn't. Interface C defines the signature for someMethodInC, but not the implementation. Class B will have to implement someMethodInC.

In C#, you can inherit from only one class, but you can inherit multiple interfaces. (Same in Java, I think.)

In C#, you can also attach implementations to interfaces by using extension methods.

public static class CExtensions
{
    public static int SomeExtensionToC(this C someC, int someInt)
    {
       return someInt * 2;
    }
}
... in code ...
B objB = new B();
y = objB.SomeExtensionToC(x);

Both the method and implemention of SomeExtensionToC will be available to any class that inherits interface C. Note that both the class and method are static, and that the first parameter includes the keyword "this" in reference to an object implementing C. Some parts of the .NET framework (LINQ, as an example) are implemented as extension methods to IEnumerable<T>.

Almost like multiple inheritance, without the bad parts. And the extension methods are still considered part of the interface, so can be considered as part of the "contract" inherent in interface C.

Cylon Cat
  • 7,111
  • 2
  • 25
  • 33
  • To confirm, yes Interfaces do also exist in Java with very similar syntax and implementation. http://stackoverflow.com/questions/3355408/explaining-interfaces-to-students/3361740#3361740 Dynamic languages offer other ways to achieve multiple inheritance. – JulesLt Aug 12 '10 at 12:14
-1

Your definition of multiple inheritance is not correct.

At the OO level, multiple inheritance is well and clearly defined.

And both C++ and Java support multiple inheritance.

The problem is that most programmers have absolutely zero OO/OOA/OOD notions and all they know are OOP implementation details. Hence their wrong belief that "inheritance" is synonym to "implementation inheritance".

However this is completely wrong.

Because Java support multiple (interface) inheritance, which happens to be the real and only form of inheritance that exists at the Object-Oriented-Analysis / Object-Oriented-Design level.

Show me any OOD resulting from an OOA and that is using multiple inheritance and I can translate it cleanly to OOP in Java using multiple interface inheritance (as an added bonus in Java the "diamond" problem doesn't exist).

NoozNooz42
  • 4,238
  • 6
  • 33
  • 53
  • However note that by altough correct and provable my answer is unlikely to be well accepted on a site like SO, which is entirely focus on implementation details and frequented by programmers who are for the most part totally unaware of the bigger picture. They've been learning OO, say, while learning Java and have been told in the process by countless totally wrong sources that Java only support single inheritance. Don't expect these kind of people to see the light and change their minds :) – NoozNooz42 Aug 12 '10 at 12:08
  • Extending interfaces in no way constitutes multiple inheritance. No implementation details are ever derived from an interface, it's merely a specification of what a class should contain (and implement). But if you're of a different opinion, feel free to elucidate. – mikek Aug 12 '10 at 15:03
  • @mikek: of course extending from several interface constitutes MI (on a funny sidenote, Java didn't get this wrong: you can write *interface A extends B,C*. And I specifically explained why in my answer "multiple interface inheritance" is "multiple inheritance". You're seriously confusing "code reuse" and "inheritance". Note that anything you think can't be done and hence ain't MI when extending from multiple Java interfaces can actually be done simply using delegation. Once again: show me **ANY** OOA/OOD using MI that cannot be trivially ported to Java using multiple interface inheritance... – NoozNooz42 Aug 12 '10 at 15:50
  • Note that the [Java tutorials](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) themselves state "Excepting Object, which has no superclass, every class has one and only one direct superclass (**single inheritance**)" (emphasis mine). Of course, this might fall under your "totally wrong sources." – Reinstate Monica -- notmaynard May 14 '13 at 17:45
  • Also note that the question included C# and Java, but not C++. – Reinstate Monica -- notmaynard May 14 '13 at 17:49