> Why is using an interface as type is recommended over class? I cannot > see the advantage of doing so.
Because, doing so, you can achieve run-time polymorphism which is quite powerful, and your classes don't have to be extended. It's like assume you have an interface for a stack, which has abstract methods push() and pop(). And you have 2 different stack classes, say, FixedStack and DynamicStack (which is growable). And each of them has different implementation of your interface (that is different implementation of pop() and push() methods). Now, in your main class, you can create a reference of interface type and then assign it FixedStack and DynamicStack objects, and doing so, you will get different implementation of methods declared in your interface depending on type of object your interface reference currently refers to. So, after you assign PersonInterface pi reference to Person object, you can use the version of methods declared in Person class, then you can assign the same pi reference to Student object, and you will get different implementation of the same methods, and so on. Sorry if my explanation is too obscure. Maybe someone else will clear things up better :) On Mar 12, 8:39 pm, [email protected] wrote: > @ page: 21 > > @ quote > ● Interfaces and classes are both types > - This means that an interface can be used in places > where a class can be used > - For example: > // Recommended practice > PersonInterface pi = new Person(); > // Not recommended practice > Person pc = new Person(); > > Question: > Why is using an interface as type is recommended over class? I cannot > see the advantage of doing so. > > Thank you. --~--~---------~--~----~------------~-------~--~----~ To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/javaprogrammingwithpassion?hl=en -~----------~----~----~----~------~----~------~--~---
