Is the above called programming to an interface or programming to an implementation?.
on page 12, programming to an interface is shown as:
So both codes seem to be 'programming to an interface' as Animal is superclass of Dog and QuackBehavior is interface or Quack subclass. Then why is the girl on page 17 complaning that we have programmed to an implementation???
I reckon most people would consider your Animal/Dog example as programming to an interface. By declaring your variable as type Animal, you are ensuring your code treats the object as an Animal, and does not use any methods only present in Dog. In particular, if you wanted to use a Cat instead of a Dog, you know you can do it by changing just this one line of code to something like:
Stan kind of skipped this step and jumped straight to the next one. In modern designs it is becoming less usual to call "new" inside domain methods. Istead we prefer to "inject" (also known as "pass in") pre-created objects. In Stan's example our code knows nothing at all about the type of the animal object, except that it implments Animal.
In your other example, you haven't really shown enough to tell if you are programming to an interface or not. You only tell us the name of the "quackBehaviour" variable, but not its declaration.
If the declaration is something like
then you are probably coding to an interface, although the name seems a poor choice. If you were to replace "new Quack()" to "new Bark()", your code would now look like
which does not make much sense.
If (as seems more likely from the name), the declaration of your variable looks more like:
Then you are coding to an implementation. You can tell this because if you try and replace "new Quack()" with "new Bark()", you get a compiler error. A Bark is not a Quack.