This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Prefering interface over class inheritance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Prefering interface over class inheritance" Watch "Prefering interface over class inheritance" New topic
Author

Prefering interface over class inheritance

sumit anand kumar
Ranch Hand

Joined: Apr 28, 2010
Posts: 83
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
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper

Joined: Aug 26, 2006
Posts: 4968
    
    1

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
Saloon Keeper

Joined: Aug 26, 2006
Posts: 4968
    
    1

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
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

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.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
I would tell the interviewer that interfaces allow for a 'plug-and-play' architecture, regardless of whether inheritence is single or multiple.

John.
Dawn Charangat
Ranch Hand

Joined: Apr 26, 2007
Posts: 249
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.
Randy Scarberry
Greenhorn

Joined: May 15, 2010
Posts: 4
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

Joined: May 15, 2010
Posts: 4
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.)


Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37884
    
  22
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
Rancher

Joined: Sep 29, 2008
Posts: 12617

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

Joined: Apr 28, 2010
Posts: 83
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.

Sujeet Kumar Jaiswal
Greenhorn

Joined: Mar 07, 2010
Posts: 17
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
Rancher

Joined: Sep 29, 2008
Posts: 12617

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.
jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
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

Joined: Apr 28, 2010
Posts: 83
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".
Dave Lorde
Greenhorn

Joined: Apr 02, 2007
Posts: 20
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

Joined: Feb 12, 2010
Posts: 266
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

Joined: Feb 12, 2010
Posts: 266
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

Joined: Apr 02, 2007
Posts: 20
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

Joined: Apr 02, 2007
Posts: 20
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

Joined: Feb 12, 2010
Posts: 266
Thanks Dave Lorde for your answers, anybody else would like to respond ?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Prefering interface over class inheritance
 
Similar Threads
Relationship
Thread interview question
Doubt in Object oriented concept
Interview questions for Java developer, Struts, EJBs
Interfaces