3

Is there a way in java to extend multiple classes? For example a Student can be referred to as a Person and also as an Animal (you get my point). If not, what is the way around it?

Kelly M.
  • 31
  • 3
  • So you claim some students are animals? :) – Konstantin Yovkov Feb 10 '16 at 14:48
  • 4
    If a Student is a Person and an Animal, then why isn't Person already extending Animal? The only way around is to think about another structure. Either by using composition, instead of inheritance, or by letting a parent class extend "the other parent class". You should try the first one suggestion first: [Favor composition over inheritance](http://stackoverflow.com/questions/11343840/favor-composition-over-inheritance). – Tom Feb 10 '16 at 14:48
  • 1
    The closest thing to multiple inheritance in java: https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html – peter Feb 10 '16 at 14:51

2 Answers2

1

No. Java does not support multiple inheritance.

You can implement multiple Interfaces (which never contain code beyond method signatures), but not multiple classes.

Tim Jasko
  • 1,532
  • 1
  • 8
  • 12
  • 3
    I would add that through default implementation (java 8) is widening the scope of interfaces ! @https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html – Louis F. Feb 10 '16 at 14:55
  • Default methods is a point to be considered @LouisF. – Nikitha Feb 10 '16 at 14:58
0

Roughly said, no. Actually extending from two classes is not possible, but if it fits your needs you can use an interface, meaning a class where you instead of inheriting methods you get a specific layout of all methods that the class has to have available. So yes with this method you can implement multiple classes as interfaces, but if you want to recall actual code written in a method from a parent class, you can't.

A possible work-around is by making more classes to inherit from in between or make a parent class that solely fits your needs as a common parent.

For example, if you're guaranteed to have students only in your code you can make that the parent class and person and animal the classes to inherit from it. But yet again, if the code is more complex or doesn't fit into this picture you won't be able to do it this way and you might have to define variables to check whether or not this specified class is a student.

Voltboyy
  • 129
  • 1
  • 8