Abstract class
Abstract classes are created to capture common characteristics of subclasses. It can not be instantiated, it can be only used as super class by its subclasses. Abstract classes are used to create template for its sub classes down the hierarchy.Abstract is object oriented. It offer the basic data an 'object' should have and/or functions it should be able to do. It concerns on the object's basic characteristic, what it has and what it can do. Hence objects which inherit the same abstract share the basic characteristics (generalization).
Interface
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. So it is kind of signing a contract, you agree that if you implement this interface, then you have to use its methods. It is just a pattern, it can not do anything itself.Interface is functionality oriented. It defines functionalities an object should have. Regardless what object it is, as long as it can do this and that (functionalities defined in interface), it's fine. It ignores any other things. An object/class can contain several (group of) functionalities, hence it is possible for a class to implement multiple interfaces.
When to use Abstract class and interface:
- If you have a lot of methods and want default implementation for some of them, then go with abstract class
- If you want to implement multiple inheritance then you have to use interface. As java does not support multiple inheritance, subclass can not extend more than one class but you can implement multiple interface so you can use interface for that.
- If your base contract keeps on changing, then you should use abstract class, as if you keep changing your base contract and use interface, then you have to change all the classes which implements that interface.
No comments:
Post a Comment