hi, i came to know many answers across for the following question.
What is the difference between an Interface and an Abstract class?
cud anyone tell me exactly..when to use which..and why we go for these..
really.. i cud not get properly this...
Thanks &Regards Chinna
Joined: Sep 28, 2004
First in an interface all members are public by default. But an abstract class can have all flavours of modifiers like public protected etc. An interface can have only method signatures but an abstract class can have method implementations.
Some times a few methods like startup & shutdown in the child classes might be in common & the other methods differ in implementation in such cases abstract classes are good because the former methods can be defined and used by the sub class & the other methods can be declared as abstract so that the first concrete subclass has to implement it.
When you think your child class satisfies "is-a" relationship then you can go for abstract class for others interface can be used.
You can't instantiate either interfaces or abstract classes, but there the similarity more or less ends. Interfaces aren't classes at all. You can extend them, but only to other interfaces. By contrast, abstract classes are made to be extended, that's their sole purpose.
Roughly, if you're thinking about a thing in terms of what you can do with it, that's where an interface is appropriate. If you're thinking about a thing in terms of what properties it has and what it does, but these properties and its behavior are so broad that many radically different kinds of things qualify, then that's where an abstract class is appropriate.
Buffer is a good example of an abstract class: you might want Buffers for a variety of data types (e.g. chars or floats), but depending on whether you've got a Buffer of one or the other you may have very different uses in mind; hence, CharBuffer has a charAt() method, but FloatBuffer() does not.
Collection is a good example of an interface: collections in themselves have no interesting properties or behaviors--all that matters about them is that you can put things into them and take things out of them. There are specific kinds of collections that have interesting properties--sets, linked lists, vectors, etc.--which is why these kinds of collections are classes.