Doesn’t Java have multiple inheritance?

Asked

Viewed 15,418 times

21

I had seen somewhere now I don’t remember, I think it was in a course on object orientation, which Ruby possesses. But in Java I’ve never seen it. Is that why abstract classes are used? Or is this meaningless?

  • 2

    Do you speak of multiple inheritance? Java does not have this, although a class can implement multiple interfaces (a interface is a "purely abstract class").

  • interface is an abstract class?(I got a little confused). Yes I’m talking about multiple inheritance.

  • It is there, yes. A class being abstract only means that it cannot be instantiated directly, it must be inherited from it for that. But an abstract class can have concrete components (i.e. fields, methods...). The rule for abstract classes is the same for other classes (i.e. no multiple inheritance at most one extends by class). The interface, on the other hand, can only have public and abstract methods (i.e. not implemented), and nothing else. Hence the "purely abstract". Every class that implements an interface must give a concrete implementation to its methods, without receiving anything ready.

  • 1

    Java não possui múltiplos extends? your title is a little confused. There is only one reserved word extends in Java, not several :P

  • I edited the title of question :D

  • But is the interface a class?? Or is it simply interface?

  • 1

    I would say interface is interface, and class is class. However, an interface is "as if it were a 100% abstract class", that is, it is not allowed to have concrete methods.

  • I can not put two right answers...actually the two helped me a lot to understand this concept. But I gave my vote for both of them.

  • 1

    Classes and interfaces are types. You can interpret the interface as if it were a "capada" class. And this is good, it solves some problems as you can see in the answers.

  • Cool, capada is good :P Interesting question the Diamond Problem was reading.

Show 5 more comments

2 answers

20


In Java it is not possible for a class to inherit multiple classes.

The reason for this, imagine that one class inherits two other classes, however these two inherited classes have methods with the same signature but with different implementations. It would be difficult to deal with, because how would the subclass know which implementation of the method it should use? So it is not possible for a class to extend from more than one class in Java.

An abstract class may have abstract methods as well as concrete methods, that is, methods that have already been implemented, so the fact that the class is abstract does not help much to solve the problem mentioned above.

What you can do in Java is that a class implements several interfaces, because interfaces are like 100% abstract classes, that is, it is completely forbidden any kind of implementation in it, therefore, there is no problem if the two interfaces have a method with the same signature, because who will implement the method is the class that implements the interfaces.

Something curious is that the word reserved extends can be used for interfaces, which is when one interface inherits another interface(s), but in this case there is no problem of an interface inheriting from several other interfaces, as there is no implementation involved in this case. It would be a code that would look like this:

Interface1:

public interface Interface1 { public void teste(); }

Interface2:

public interface Interface2 { public void teste(); }

Subinterface:

public interface SubInterface extends Interface1, Interface2 { }

Note that there is no problem in doing this, because the implementation goes in the first concrete class that implement the Subinterface:

public class MinhaClasse implements SubInterface {
    @Override
    public void teste() {
        System.out.println("sou apenas um teste");
    }
}
  • I mean that in an interface I can make extends of more than one??

  • @Rogerscorrêa yes! That’s why I used the word curioso in my text :D See my edition, I put code in my reply

  • Yes. I understood. So I questioned to see if I had understood correctly.

  • 1

    Really worked with interface

  • 1

    If it is not possible to know which class to use, then pq c++ has multiple inheritance? It is capenga?

  • @Fláviogranato I had to search to answer your question, and I arrived on this site here. Apparently it is so: Com uma pequena convenção de assinatura, do tipo, a classe que vier declarada primeira, terá o controle de sobrescrever os membros em situação de conflito de nomes ou qualquer coisa do gênero. However this functionality seems to give more headache than solutions, and as Java is to be a simple language, they chose not to allow such functionality. I wouldn’t say C++ is lame, it’s just not as high as Java.

  • :-) I understand. When she said it, I meant Java. Yes it changes only the algorithm of resolution of dependencies, already quoted below... with the defaults methods to me it became very evident that it could have had multiple inheritance long ago, it was only laziness and an equally lazy justification. I’ve been a Java programmer for 10 years, only because it gives me more money than the other languages, not belittling them and not even Java... because I’d like to go to another world... hehehehe

  • @Fláviogranato disagree. See in that reply what it says: Somente use herança se o subtipo puder perfeitamente substituir o tipo base, If you manage to replace two different base types it means that you hurt the principle of sole responsibility, otherwise that was it then you duplicated code because one of the base types should not exist. Soon, the multiple inheritance will always end up hurting some of the principles of OO, so in my opinion Java hit the nail on the head in this decision, this is just one of the reasons why I love this language.

  • now yes, a guy who only uses language to make money and another who loves... the fact is that java is patching up a lot to have things she could have had a long time ago, default methods is simply laziness to implement multiple inheritance. Liskov applies to the moment I’m using the language, not to the compiler as we begin to speak, from my point of view you’re changing the direction of the answers simply to win the discussion, Well, I guess I just gave up on losing energy over discussions about the sex of angels. Inté more...

  • @Fláviogranato did not understand your arguments well, I am not trying to impose myself, I just said my opinion, maybe you are right and I am not seeing something you are (without irony), I never felt a real need for multiple inheritance, maybe one day I feel. But one thing I agree, I think the conversation is no longer productive, rs.. let’s call it a draw then, since apparently we didn’t win anything with it.

  • 1

    This discussion of yours is much more theoretical than practical. Apparently neither of them worked with a language that has multiple inheritance and never saw good codes with it. Soon, it is easy to say that it is capenga and that it hurts the principles of POO. Want an example? Look at the Django-Rest-framework code and how simple it is to create a class that has the behavior of another two through multiple inheritance. And Java is far from being a simple language...

  • By the way, when I went to learn Java and found that there was no way to do multiple inheritance and that to achieve something like that you would have to use interfaces and blablablablablabla, my head exploded with so much complexity to do something simple in other languages.

Show 7 more comments

18

Correct conceptualization

I think you are looking to know if Java allows multiple inheritance. In it the class can inherit from several other classes, whether concrete or abstract.

Abstract classes are those that cannot be instantiated, that is, that you cannot create an object based on it. They only exist to be inherited. They must be part of another class. Your methods may or may not have implementations.

A special case of abstract class is the interface. It cannot have been (roughly, variables that hold values) and methods cannot have implementation (in Java 8 can). It has only the signature of the method defining the behavior but not how the behavior will act. It is considered a purely abstract class because it has not been.

In Java you can get multiple inheritance of interfaces through implements. That is, you can inherit several sets of behaviors without defined implementations but cannot inherit state and implementations at ease. Only one concrete or abstract class can be inherited. If you need to add other features in the new class it must be through specific implementation.

You can use multiple implements, that is, you can implement as many interfaces as you need to indicate what that class is capable of. When you extend, you’re saying the new class is an "improved version" of the class that will be extended. When you implement something, you are saying that the class has certain characteristics necessary for its proper functioning. This way you and the compiler know if a class can be used in a given context. That is, if she possesses all that will be necessary in that context.

This was partially minimized with the new Default Methods in the interfaces.

Using "multiple inheritance"

I don’t know Ruby well, but as far as I know she also doesn’t have multiple inheritance. She does this through mixins. A combination of features is made and not exactly a heritage of resources. It is similar to interfaces with default methods.

So in Java 8 it’s possible to have something very close to what Ruby gets. Being a new resource I still don’t understand all its limitations but it is clear that there can be no state and there can be no constructors as occurs in concrete or abstract classes. It seems to me that are similar limitations to those found in mixins.

Note the examples of the Java documentation on default methods that it is possible to add complete behavior, that is, defining your signature plus the implementation, but this is not considered de facto multiple inheritance. It’s more of a combination. Of course popularly it can be interpreted as being.

It seems to be a trend that all languages have some form of combination of methods, or with default methods, or with Extension methods (C#) or with mixins or with traits (PHP). Without such resources, it forces the programmer to violate the DRY and copy identical implementations to methods that do exactly the same thing in different classes.

Simplified example:

interface Teste {
    default public void teste() {
        System.out.println("teste");
    }
}

class Classe { };

class NovaClasse extends Classe implements Teste { }

class HelloWorld {
    public static void main(String[] args) {
        NovaClasse teste = new NovaClasse();
        teste.teste(); //vai imprimir a palavra teste conforme definido na interface
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Problem of multiple inheritance

Multiple inheritance is discouraged because of the diamond problem and the difficulty of correct implementation in languages. In addition, programmers have difficulty understanding the functioning and constraints that it imposes. There is often abuse using multiple inheritance as a mechanism to facilitate coding when it should facilitate semantic organization of the application.

Few languages implement this feature. C++ is one of them but it is recommended to avoid at most. Eiffel is a case that even encourages but is a language that has other limitations. Smalltalk also allows. Some features are not very orthogonal, and do not match well. So it is necessary to make choices.

  • Then I could do 1 extends in a class with various Implements?

  • See if the edition improved this understanding.

  • Yes I understood better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.