I have seen mentioned at several places that class adapter pattern cannot be done in Java (including Head First: Design pattern and Implementing Class Adapter Pattern in Java on SO). I cannot understand why.
Consider the following adaptee, target interface and adapter code:
Object to be adapted (adaptee)
class Adaptee{
int id = 123;
void doStuff(){
/* Doing stuff */
}
int getId(){
return id;
}
}
Target interface
interface TheNewInterface{
void doAction();
int getId();
}
Object adapter
class ObjectAdapter implements TheNewInterface{
Adaptee adaptee;
ObjectAdapter(Adaptee adaptee){
this.adaptee = adaptee;
}
@Override
void doAction(){
adaptee.doStuff();
}
@Override
int getId(){
adaptee.getId();
}
}
Class adapter (??)
class ClassAdapter extends Adaptee implements TheNewInterface{
@Override
void doAction(){
doStuff();
}
/**No need to provide an implementation of getId() as super class has it implemented*/
}
Why is it said that class adapter is not possible in Java? The reason for this is mentioned that Java does not supported multiple inheritance.
But per definition the ClassAdapter
class is exactly that - conforms to the new interface & at the same time IS of adaptee type.