0

I have a question regarding interfaces. If I have an interface Printable which has (for example) a method "print", and I create a class Book which implements the interface, I can create an object of Book in two different ways:

Book b = new Book();
Printable b1 = new Book();

I know that I can only reach the methods declared in the interface Printable if I create the object using the second method, but why do we have this option? In which cases would one want to only access the methods declared in the interface, and not be able to access the other methods that are specific to the class in question? Maybe a stupid question, but I don't understand the use of the second option shown above.

user16655
  • 1,901
  • 6
  • 36
  • 60
  • that's how to use interfaces. everything deals with the question how to hide implementation and make coding interface as small as possible to have minimum dependencies. – Aitch Feb 09 '15 at 17:08
  • 3
    See [programming to an interface](http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – GriffeyDog Feb 09 '15 at 17:09
  • lets say your print method prints both side for book. Now you have journal that implements Printable and the print method only prints 1 side every page for journal. You receive request to print, mixed of journal and book. If you had used second way to create both book and journal, You can add all request to list of Printable type, regardless of Bokk or Journal type. Now you iterate the loop and call print method, all journal will be printed one sided , and books will be printed both sided. You dont have to worry about the specifics and print them manually one sided or both. – Jimmy Feb 09 '15 at 17:43

0 Answers0