About abstract, interfaces, and when i should use this.
Hello everybody. I am new in Java Programming, but i have a very strong interest with this Java Programming.
I want to ask about abstract, interfaces, and when i should use this. I have learned and read the references that explained the teory, but i wanna know in reality. Meaby there are one of you that will explain me about my confussion above, oh ya, meaby i am easier to understand with example than theory.
Thank you very much for the explanation to me. :)
Re: About abstract, interfaces, and when i should use this.
There is a relatively old book which coined the phrase "program to an interface, not an implementation" - its great advice. The reasons why are numerous, suffice it to say it loosely couples things together, making code easier to change, reuse, etc...
Java has many great examples worth studying. For example listeners found in Swing - an article that describes a way to write this sort of thing can be found at http://www.javaprogrammingforums.com...r-pattern.html
Another example is sorting provided by the Collections class. All the sort methods cares about is the Comparable interface - generally speaking, this is an example of how one can write algorithms around a single interface, which allows that algorithm to operate on just about anything (so long as that 'anything' implements the interface). Another example would be the Collections framework - List, Map, Set, each has multiple implementations however often all you are about are the base methods provided by the interface.
BTW The quote above is from a book called Design Patterns by the "Gang of Four"...google 'java design patterns' for more information.
Re: About abstract, interfaces, and when i should use this.
An interface is something used when you want to implement functionality in the future. Interfaces must have their methods defined by the classes that implement them. Abstract classes allow you to implement their methods in the abstract class and then re-define them if you wish in sub-classes.
When copeg said, "Program to an interface, not an implementation," he meant that an object should be written in an abstract form (not necessarily with abstract classes) so that it can easily be reused. As a rule, class hierarchies should be avoided:
Code :
class Foo
class SuperFoo extends Foo
should be:
Code :
class Foo
class SuperFoo
{
Foo foo;
}
Always favor object composition over inheritance.