AnonymousAlias
AnonymousAlias

Reputation: 1399

Are we using the adapter design pattern everytime we extend a class and implements its interfaces methods?

My understanding of the adapter design pattern is that we are allowing an interface from an existing class to be used as another interface.

So every time we extend or implement a class in java we are using the adapter pattern? So this bit of code here is using the adapter design pattern?

public class car extends flyingMachine{

  void drive(){}

  @override
  void fly(){}

}

There is lots of information on the pattern online but nothing that clarifies this question for me.

Upvotes: 0

Views: 384

Answers (1)

KevinO
KevinO

Reputation: 4403

No -- inheritance is not an adapter pattern.

Say you have your Car with your drive() method (which really should implement an interface say Moveable with the method drive()). Now there is some other class that take a parameter of Moveable.

public class MakeItSo
{
   public void easeOnDown(Moveable thing)
   { 
      thing.drive();
   }
}

Now let's say you have a cool new class Spaceship provided by someone else, and it has a method warp(). And it doesn't implement Moveable, but you'd like to use the MakeItSo class. What to do?

This is where the adapter pattern can help. In such a case, you create a new class that implements (or it could extend, but that is very confusing in many cases) the Moveable interface, but is:
- Constructed using the Spaceship
- Allows the drive() method to call the warp() method

public class MoveableSpaceship implements Moveable  
{  
    private Spaceship ship;

    public MoveableSpaceship(Spaceship s)
    {
       ship = s;
    } 

    @Override
    public void drive()
    {
       ship.warp();
    }
}

Now you can do:

Spaceship enterprise = getSpaceship();  //from wherever
MoveableSpaceship ncc1701 = new MoveableSpaceship(enterprise);
MakeItSo doIt = new MakeItSo();
doIt.easeOnDown(ncc1701);

So, even though MakeItSo.easeOnDown only knew about Moveable, and the Spaceship didn't implement Moveable, using the adapter pattern it is now possible to use the MakeItSo class with a Spaceship object via the adapter pattern.

Note: updated class to match a comment that I originally didn't interpret correctly.

Upvotes: 1

Related Questions