• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

multiple inheritance

 
Saad Ahmed
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, you always see people say Java doesn't support multiple inheritance but can someone explain what is the difference if a class implements an interface that extends from multiple interfaces? Isn't that the same thing?
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, nothing can extend from multiple anythings.

It might *implement* multiple interfaces, but any given class can only *extend* a single other class.

Also, if my class does something like this:
The Car class implements two interfaces, Vehicle and Motorized. But this is not the same as multiple inheritance. Multiple inheritance generally means that you inherit not only the interface but the implementation. But in Java you can only 'implement' multiple interfaces.

So in C++, if my Vehicle and Motorized where classes, then yes, my Car class could extend both of them, and I'd have to write no additional code, if I were satisifed with the behaviour provided by my two parent classes.

But in Java, I only 'implement' the interface and I have to provide this implementation for both of those interfaces.
 
Saad Ahmed
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not exactly what I meant, let's say:
public interface A {
String getMesg();
}
public interface B {
String getMesg();
}
public interface AB extends A, B {
}
public class implements AB {
String getMesg(} { return "hello"; }
}
This is valid...so Java does support multiple inheritance by interface...I want to know what are the major benefits of class-based inheritance?
 
kyle amburn
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi-
Consider this:
interface Controls
class Car
class VWBug extends Car implements Controls
class Airplane implements Controls
Now the interface Controls has methods for braking(), accelerating(), etc. If these methods were put in a class then a implementation of these methods would be possible. However, you would not want to allow a basic implementation of braking() for a Airplane as opposed to a Car since they each do these operations differently. You cannot have a Car that is a vehicle and at the same time is a Airplane. If Airplane were an interface then the methods would only be methods that you implement.
Kyle
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic