Editor's note: Sometimes, the most interesting discussions begin when someone says, "This may be a stupid question, but ...." If the person asking the question has taken the time to think about the problem before asking, the question is often not stupid at all. Uncertainty points out an ambiguity in specs, holes in docs, or a search for how more experienced programmers might address a particular problem. From time to time, we will publish one of the "(Not So) Stupid Questions" we receive and invite our readers to answer the question in the feedback section.
Remember that new people are joining the Java community all the time and may be looking for help from those with more experience. Also, those who began with Java as their first language can benefit from those coming to the community with experience in other languages. As always, answer the questions with kindness. You are also welcome to submit your questions to
This may be a stupid question, but ... "When should I implement an interface, over inheriting from a parent class? "
First thoughts:
I know this is done to avoid multiple inheritance, but I also know that you can write an interface and implement it instead of using inheritance. This arrangement allows you to implement behavior defined by many different interfaces, but stay out of the trouble that would ensue if, for example, you could inherit from two concrete classes and both had a method with the same name and same parameters.
An abstract class is kind of like an interface, in that it's meant to be extended, but your class can only inherit from one class, abstract or not. That seems different than implementing an interface anyway, since the abstract class can provide method implementations for subclasses to inherit, something interfaces can't do.
This brings me to two questions:
1. Should we completely avoid inheritance, and only use interfaces? and
2. If so, how will analysts know whether to continue to construct analysis class models using inheritance?
"(Not So) Stupid Questions" is where we feature the questions you want to ask, but aren't sure how.
Programming to Interfaces.. HOW?
2005-11-07 05:51:53 aabhijit
[Reply | View]
I feel that the importance to interfaces and the fact about programming to interfaces is just way too overrated. I mean whatever you do you just cannot "program" to an interface. There has to be some place you need to write the actual code!
I mean imagine having 'Exception' as an interface or for that matter what if 'Object' had been an interface?
I agree with some of the users who state that interfaces should be only used if you need to pass around objects with completely different functionalities per se. Any common code should be moved to the parent class.
Another way of looking at it
2005-10-19 01:35:20 rickcarson
[Reply | View]
Classes are Nouns
Methods are Verbs
Interfaces are Adjectives
Another way of looking at it
2005-10-23 14:50:25 grlea
[Reply | View]
When should I implement an interface, over inheriting from a parent class?
2005-10-18 07:27:27 aeyli
[Reply | View]
This question actually belongs to Object Oriented paradigm, so I'll try to answer from that point of view.
In simple words, Inheritance means Interface + Implementation, whereas Interface as its name suggests has no implementation. Also with the use of Inheritance, the properties of parent class propagate into the child. Lets take an example to make it more clear.
Lets say we have a class Singer, that represents a human singer. Now, singer can also be a bird or a musical instrument like Piano etc too. If we make a Singer a class then we have to take care of the issue that inheriting Piano from Singer might not work as both classes dont lie in the same category. Singer is a human (living being) whereas Piano is a non-living thing. So, instead of inheritance we can make an interface say Singable and we can implement it on Piano, Human, Bird etc.
From technical point of view, if we see collection classes, very few of them are related by inheritance, but many of them need to provide the same functionality.
The way that you provide the same behavior in otherwise unrelated classes it to use interfaces.
Hope it helps.
When should I implement an interface, over inheriting from a parent class?
2006-01-30 10:28:23 swatdba
[Reply | View]
I think this is a very good point. A class realizes an interface whereas inherits from a superclass. Without inheritance we would moving back to the same one dimensional world as was true with procedural. However that one dimension would be behavior rather than state.
Use both
2005-10-17 08:46:17 abhijit_jadeja
[Reply | View]
Use inheritance for internal code reuse and interfaces for contract definition.
Dont let the language define the problem!
2005-10-15 04:53:17 siver
[Reply | View]
I read the question and thought that it was interesting that although I've designed and coded a number of programs I never really been stuck at whether to implement something as a subclass or an interface. I think the reason for that is I don't worry too much about reusability and hiding code (the technical aspects of coding) in my first few attempts at my model. I simply try to describe the problem domain as clearly as I can with whatever makes the most sense to me at the time, e.g. A Chevy is a Car, inheritance or a Car is Driveable an interface. I use whichever "sounds" more appropriate for the problem at hand. I don't think that one is more correct than the other. I don't burden my model with constraints that are unlikely or unnecessary for the problem at hand. My model covers only a particular slice of reality not the whole thing as a result the problem could probably be solved with either approach. What you gain in functionality and speed with one solution, you may lose in clarity and maintainability and vice versa. Although it might be quite the CS quandry to think about pros and cons of inheritance vs interfaces in the abstract I am an engineer and practically speaking most real problems tend to lend themselves to one or the other design quite intuitively. At least this has been my experience.
interface definition is a design-time resource, inheritance is an implementation-time resource
2005-10-14 09:09:22 rivasdiaz
[Reply | View]
As the famous GoF book says:
Prefer interfaces over inheritance.
Use interfaces as a design-time resource when you are planning your system. Inheritance should be used almos always to reuse code. If your system is designed based on interfaces, it will be easier to maintain and to evolve. Of course this is not a fixed rule, but it works most of the time.
Interfaces and abstract classes
2005-10-14 06:59:51 krismoum
[Reply | View]
I think interfaces should always preferred to concrete implementations. It is almost always useful to define a contract of functionality for a given set of features. Clients of such a contract should never have to bother with details of actual implementations. However, common functinality should be placed in abstract classes implementing an interface. This is a much more flexible approach.
Also - favour protected scoped methods rather than private scoped with regards to concrete classes. If a method really has to be private, declare the class final instead. This way you can unit test your code from a testcase which is located in a mirrored directory mapping the same package structure as the actual application source.
Templates & common things
2005-10-14 04:12:12 ctreber
[Reply | View]
I often start out with interfaces, and while I code I find that implementing classes have certain methods and fields in common. So I convert the interface to an abstract class which implements common methods and fields.
Another thing is template methods: an abstract class provides methods (with code) which rely on abstract methods implemented by classes that extend the class. You can't do that with interfaces. (of course, you could implement the abstract class and use an interface to call the to-be-implemented methods, but then you've already got two articfacts).
That all said, I'm all for interfaces and use them as much as I can where it seems reasonable to do so.
Chris
Templates & common things
2005-10-19 00:02:08 rickcarson
[Reply | View]
I heartily agree with what Chris said. Start with interfaces. Then when you find common behaviour, promote it to a superclass, abstract or otherwise.
I'm not anti inheritance. I strongly disagree with comments like inheritance being wrong 90% of the time. Inheritance is a powerful tool. To truly master OO you will be comfortable with both inheritance and interfaces.
Since inheritance is taking a bashing, let me provide some additional food for thought. You can have a 'conversation' between a class and its superclass, where your methods on the superclass call methods on the subclasses.
Eg lets say you have some classes that spit out messages composed of tags. You might have a central method (the 'controller') which orchestrates how the message is assembled. This controller might call a getHeader() method. Lets say that most of the subclasses are going to spit back a standard XML header. Okay, so we move that implementation up into an abstract superclass of the controller or the class of the controller. But - there's always a problem child. Lets say one of the subclasses needs to return an HTML header instead. No problem! Just override the getHeader() method in that subclass.
This allows us to deal very easily with special cases. Business rules are absolutely notorious for this, there always seems to be an exception to every rule.
So here we have the case where inheritance has made the general case easier, and also made the special case easier... so long as the superclass is designed properly.
Hope you found that helpful.
Interfaces the way to go
2005-10-13 19:49:09 grlea
[Reply | View]
Daniel asked, in his Editor's blog, "Is it still OO if we don't get to subclass?" I think it is. I don't think that inheritance is a core feature of OO programming. While it's definitely an extremely useful feature (no polymorphism without it), the absolute core feature of OO is having the code located with the data, and that feature is not lost if you lose inheritance.
On the inheritance vs. Interfaces argument, I am becomingly increasingly convinced that interfaces are of the utmost importance. With the bulk of my work over the last year being refactoring, it has been clear that, had the original authors used an interface inheritance hierarchy instead of a concrete inheritance hierarchy, my job would have been as simple as creating a new implementation of said interfaces. Instead, it has involved masses of refactoring, extracting super classes and interfaces, moving methods, changing code everywhere to not refer to concrete classes that are no longer applicable.
There are definitely some people who use inheritance WAY too liberally. It must be an "is a" relationship. A Human is a Mammal is an Animal. But a Request is not a HashMap. It may consist largely, or even solely, of a map of values, but that does not mean it IS a map. This is particularly important, because the request may evolve to become MORE than that. No matter how you Human class grows, it will always be a subclass of Mammal.
The most important thing, though, I feel, is planning. Interface and class hierarchies need to be planned, and reviewed and scrutinised, ideally at a team level. Once you have the right hierarchy, the most sensible thing you can do is to only ever program against the interfaces, even hiding the concrete classes from existence (using package or private visibility) if possible.
</twocents>
Graham.
language support
2005-10-13 11:58:57 dog
[Reply | View]
If it is true that delegation should be preferred over inheritance, then there should be a language supported way to do it easily (since the language should support best practices). For example:
class MyClass {
// this would make method1() work from this
// object
delegate OtherClass.method1;
}
language support
2005-10-13 15:59:19 prunge
[Reply | View]
I agree.
inheritance is overrated
2005-10-13 08:10:42 smbell
[Reply | View]
Just my opinion,
9 times out of 10 inheritance is the wrong tool for the job. In the case where there is desired reuse of functionality it is usually a better solution to use encapsulation (has a rather than is a). There are cases where inheritance is very useful, however you should think carefully before using it, and make sure that superclasses are written with inheritance in mind.
Joshua Bloch's book Effective Java covers several of those points.
inheritance is overrated
2005-10-13 08:40:11 wireframe
[Reply | View]
agreed. extension should be used sparingly and only when it can truely be justified.
inheritance is overrated
2005-10-13 11:59:11 soticia
[Reply | View]
Not only use interfaces rather than extends. Also use interfaces for java beans, but not creating and implementation of that interface, using a proxy (JDK or Spring)