In Effective Java, Joshua Bloch favors interfaces over abstract classes. However, he notes that a skeletal implementation should come with every interface.
I feel that a skeletal implementation is almost the same as an abstract class. How do these two concepts differ?
Edited after re-reading the aforementioned section in Effective Java
According to this section of the book a skeletal implementation is an abstract class. He recommends this approach because, after a skeletal implementation is in place, it becomes trivial to implement the interface and selectively override methods, even with an anonymous class (as he does in his book).
Previous answer, edited slightly for continuity
A skeletal implementation could theoretically be a complete implementation and therefore concrete. Then it could be used with composition, because it can be instantiated. Whereas abstract classes require inheritance.
What he means is that you should provide an interface, and an abstract class implementing parts of this interface:
public interface Foo {
void bar();
void baz();
}
private abstract class AbstractFoo implements Foo {
...
}
The AbstractFoo
class may even not be abstract if it's possible to provide a basic, complete implementation. But if you need a class that is a Foo, but can't extend AbstractFoo, it's still possible with an interface. An abstract class doesn't provide this capability, since you can only extend one class.
BTW, this is what is done in the collections framework (which Josh Bloch created): the Set
interface is implemented by AbstractSet
, the List
interface is implemented by AbstractList
, etc.
The interface / abstract class is part of the API.
The skeletal implementation is a valid concrete class
, but a limited / naïve / poor implementation; for (a very contrived) example, a skeletal implementation of a Sorter
interface might implement bubble sort - you wouldn't want to use it in a production application, but it illustrates how one might implement the interface
I feel that a skeletal implementation is almost the same as an abstract class. How do these two concepts differ?
To me, they differ in intent. When I see some method expects an interface to be passed in, I know that the implementation is up to me. If a class is returned, I'm no longer sure. There's simply a meaning to the use of an interface that doesn't exist for a class.
Also, methods that accept classes for arguments invite conflict when the class we'd like to pass in is already a subclass; Java doesn't support multiple inheritance. Interfaces don't have this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With