What is the difference between abstract class and an interface? where should one use abstract and where should one use interface? please explain with a simple example.
sravi
A class can have abstract methods and non-abstract methods.
But interfaces can only have abstract methods. Interfaces are always abstract, and you do not have to specify it.
Interfaces can only have static & final variables. An interface could extends many interfaces, but a class always inherits from another class and can implement severals interfaces.
An interface can be seen as a "view" for an instance, and offer you the way to handle objects without knowing his implementation.
Let see an example. In Java, you have events(clicks for example), they trigg messages, which are received by objects. An object has to be the type of "click receiver" if it wants to catch click messages. In fact, the real type is ActionListener, which is an interface. If ActionListener was a class, all the objects that want to receive clicks messages will have to inherit from that class, which is not really practical. That's why ActionListener is an interface, in order to add easily the corresponding features to any object no matter his class.
An interface defines the signatures of a set of methods, but not the contents.
When a class implements an interface it must define the content of the methods.
When a class extends another class it inherits the filled in methods of the parent.
A class can only extend a single class but implement more than one interface.
An 'abstract class' has some methods with content (like a normal class) and some method signatures (like an interface). The methods with signatures only are where a general method is impossible to define, but one must exist. My home ---->
I think the differences between an interface and an abstract class are not very hard to understand. The important part is to know when to use an interface and when to use an abstract class. This goes into Object-Oriented design. Typically an interface will be used as the base of a class hierarchy to enforce a contract. A typical use of an abstract class is to define some basic class behavior. A good example for interfaces is the Collections API and a good example for abstract classes is the AWT Event Adapters. Both interfaces and abstract classes cannot be instantiated but can be used as references to their subclasses.
Wushutwist
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.