• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Prefering interface over class inheritance

 
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I recently attended one interview, there was one question that was asked.

Interviewer: Forget that java can extend only one class.Let suppose it supports multiple inheritance through class extension. Now why should i use interface.We can create a base class and give a default implementation of our function. And the child classes can choose to override our method. Still why would you prefer using interface.

My Answer: Interface is generally used in APIs . Its basically a contract which tells what to do but not how to do. (He was not satisfied and wanted more). I said since interface is not a part of the inheritance tree structure, the object created would be less bulky.

But the interviewer was not satisfied with the answer, and wanted me to look more.
Please suggest answer to his question
 
author and cow tipper
Posts: 5009
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Moving to Java in General, although thought about putting it into the Job Interview section. (Bartender Note: Probably should have deleted this in the ORM forum too, but chose the wrong option. Ooops)
 
Cameron Wallace McKenzie
author and cow tipper
Posts: 5009
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'd tell him that Java does support multiple inheritance. You can implement as many interfaces as you like, and interfaces represent an is-a, or inheritance type of relationship, with many other types. Sure, you're inheriting unimplemented behavior, but that doesn't mean it's not inheritance. And that's the point, since the behavior is unimplemented, you have infinite flexibility in how you code it. That's INFINITE flexibility. That's not just a bit, or more, or 'a lot' of flexibility. It's INFINITE!

I'd tell him that sure, you can only extend one class, but that doesn't mean you can't have multiple inheritance. In fact, interfaces can extend multiple interfaces, which just proves the point further.

I'd then tell interviewer that his question was actually based on FUD often propogated by people who know very little about Java, or have their heads buried in C++. I'd then tell him that I'd never work for someone with such a lack of understanding of an elegant language like Java, and then I'd get up, walk out, and slam the door behind me.

Did you do any of that? :P

-Cameron McKenzie
 
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'd tell him that Java supports multiple inheritance in a way that does me almost no good. Since interfaces don't define any implementation, I end up either having to write the same code over and over, or litter my code with delegate calls. Unless he was trying to engage in a silly conversation about the diamond problem, it's kind of a boring question.
 
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would tell the interviewer that interfaces allow for a 'plug-and-play' architecture, regardless of whether inheritence is single or multiple.

John.
 
Ranch Hand
Posts: 249
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I will still go with interfaces - because I take a leaf out of my C++ days wherein I had my hands burned using multiple inheritance.

If you have multiple super classes, and you wish to invoke a method from one of them, you need to take extra caution in deciding which one it would be - because, more than one superclass could have an implementation of the same method. Also, by doing this I would be tightly coupling my code (read Very Bad Idea !!!)

Interface can get you the same luxury, but in a more elegant and risk free way.
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sounds like what he was asking was: "Why would you bother with interfaces if Java supported multiple inheritance?" Well, interfaces weren't devised only to make up for Java's lack of multiple class inheritance. An interface defines the software contract, not the implementation. Interfaces give you the flexibility of doing the same things in any way you can conceive, as long as each way satisfies the contract.
 
Randy Scarberry
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
BTW, I've been conducting lots of interviews lately. I just might use that question next time. If anyone gives Cameron's response, I think I'll chase him/her to the parking lot, drag him/her back in, and make sure he/she gets hired.

(We really need a neuter pronoun in the English language.)


 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Randy Scarberry wrote:(We really need a neuter pronoun in the English language.)

When I was at primary school, we recognised "common gender" which appears to have gone out of fashion, so "child" would be common gender, whereas boy and girl were masculine and feminine. The "common gender" pronoun was "he". On this side of the pond, many people use "they" as a common gender pronoun nowadays.
 
David Newton
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Dawn Charangat wrote:Interface can get you the same luxury, but in a more elegant and risk free way.


I don't find interfaces to be particularly elegant. If Java had a way to actually share implementations maybe I'd be more impressed--as it is, either my IDE or I have to type a lot, and I have stuff I'd rather do.
 
sumit anand kumar
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

sksumit kumar wrote:I said since interface is not a part of the inheritance tree structure, the object created would be less bulky.



Great response Cameron Also Dawn Charangat adds one imp. point
What do you think about this quote? I long time back had surfed net and found this. But i can't relocate that.
Maybe if somebody could throw some light on it, it might be of some great help.

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

sksumit kumar wrote:

sksumit kumar wrote:I said since interface is not a part of the inheritance tree structure, the object created would be less bulky.




Actually, when the class implementing the interface is polymorphically assigned to the interface type variable, only interface portion of object is copied to the variable (phenomena called object slicing). Since interface normally has less variables (only constants) as compared to base class, I think it will be light weight.

Comments are invited over this answer.
 
David Newton
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm not sure I'd classify that as being "light-weight", and there's no "copying" -- it's just that the reference to the interface only has access to the interface's members. The object is still the same object.
 
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sure, you're inheriting unimplemented behavior, but that doesn't mean it's not inheritance.




so when we say :



I had this same question shot to me once and when I answered "yes it extends" he gave a surprised look. I then replied that it extends only the declaration part of the method.
 
sumit anand kumar
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

jose chiramal wrote:




I had this same question shot to me once and when I answered "yes it extends" he gave a surprised look. I then replied that it extends only the declaration part of the method.



code not correct

Use this.
Also i am still waiting for my question regarding "use of interface helps code execute faster".

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

jose chiramal wrote:I had this same question shot to me once and when I answered "yes it extends" he gave a surprised look. I then replied that it extends only the declaration part of the method.



Well, not really - in Java both are keywords and have distinct semantics. You 'implement' an interface and implement its methods. Implementation is to provide code that satisfies the method contract.

You 'extend' a superclass - as the keyword suggests, the implication is of adding to (extending) the superclass implementation.

A major argument against multiple inheritance of implementation, apart from the 'diamond' problem of inheritance of a single grandfather class via multiple superclasses, and the problem of ambiguity resolution for multiple identical method signatures, both of which can be solved (as in C++), is that it makes compilers very complex and correspondingly difficult to test.

Where the equivalent of multiple inheritance of implementation is required in Java, it can be effectively achieved via interfaces and composition with method forwarding, i.e. forwarding the interface methods to member objects that implement the interface. Any competent IDE will generate the forwarding methods, so there's little extra development effort. An advantage of this technique is that it lends itself particularly to dependency injection. This gives added weight to the 'Prefer Composition over Inheritance' aphorism.
 
jose chiramal
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Imagine this scenario :

I have a class Car(it has methods enginespecs and color), and there are two sublcasses to it, BMW and Toyota

In this scenario how do I know whether to use an interface or class hierarchy.
 
jose chiramal
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Also I read this point "If you need to change your design frequently,
you should prefer using interface to abstract."

In the code ranch faq i read this : "use an interface if you're sure the API is stable for the long run"


Aren't both these statments contradictory ?

 
Dave Lorde
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

jose chiramal wrote:I have a class Car(it has methods enginespecs and color), and there are two sublcasses to it, BMW and Toyota

In this scenario how do I know whether to use an interface or class hierarchy.



This is not as simple an example as you may have intended, because from one point of view BMW and Toyota are not strictly cars, they are manufacturers of cars, so BMW and Toyota Cars could be seen as a Car subclass of, say, RoadVehicle, that has BMW or Toyota as its Manufacturer or Make attribute. So much depends on what use the class hierarchy is intended for - you always have to compromise because you can only partially represent the real world in an object hierarchy, and only those aspects that are relevant to your application. For example, suppose you wanted to divide Car into subtypes such as FourByFours, Compacts and Saloons - how would that work if BMW and Toyota were subclasses of Car? I'm not saying it's not correct, just that it needs careful thought in terms of your current and possible future requirements.

At work, we have a large data entry & processing server application with a complex client GUI, and we have spent a lot of time over the last year refactoring it to make much more use of interfaces because they make it much easier to test, refactor, extend & enhance, and to use DI (Dependency Injection) frameworks like Spring.

My own rule of thumb for when to use interfaces is to always use them wherever you have a type in your model. It may seem like overkill, but I've come to the view that application design should be done entirely in terms of interfaces. The main problem with using abstract classes instead of interfaces is the reduction in flexibility it gives you - instead of multiple inheritance you have single inheritance - you're stuck with the implementation of that abstract class, even if it turns out to be unsuitable, whereas you can always add a new and completely different implementation of an interface. You can use abstract classes for shared implementation used by subclasses. By using interfaces throughout, you lose nothing and gain clarity and flexibility.

When passing parameters and returning values, always use interfaces, and all public methods should be implementations of interface methods. You only need to see the concrete classes when you're creating instances of them.

So my approach for your example would probably start with interfaces Car and Manufacturer. AbstractCar would implement the Car interface with all code common to all cars, and would contain a Manufacturer constant. If there were subtypes of Car, such as FourByFour, Compact and Saloon, I'd make them interfaces too with abstract implementations. This way, you end up with an interface hierarchy and a parallel implementation hierarchy, something like this:Note that I use AbstractXxxx for abstract superclasses and XxxxImpl for concrete classes that implement an interface. It makes it easier to write and follow the code.

This is just an example of how I use interfaces & abstract classes, it's not meant to be a 'correct' design for any particular application.
 
Dave Lorde
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

jose chiramal wrote:Also I read this point "If you need to change your design frequently,
you should prefer using interface to abstract."

In the code ranch faq i read this : "use an interface if you're sure the API is stable for the long run"


Aren't both these statments contradictory ?


A good question - I think it means that 'design' in the first guideline is not the same as 'API' in the second. The thing about interfaces is that they define what a type is and what it does - that's what the API specifies, known as the 'contract'. How each object does what the API specifies is something else. But if you haven't decided exactly what a type is and what it does, it's not ready for use. Once an interface is specified, it should not change.

The design (as used in the first guideline) is about how you use the interfaces in your application - how you implement them and how you get the implementations to interact with each other. Interfaces give you great flexibility because you can implement them however you want, and if you only pass interfaces around within your application, you can add new implementations with minimal code changes.
 
jose chiramal
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Dave Lorde for your answers, anybody else would like to respond ?
 
eat bricks! HA! And here's another one! And a tiny ad!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic