It is a bit confusion about when to use an abstract class and when to use an interface.So lets see the differences between abstract classes and interfaces,so that we can use them appropriately!!
Let us consider a class wholesaler which represents a wholesale shop with textbooks and stationary like pens,
pencils,papers and notebooks
let us consider a class RetailerA, which represents a retail shop. RetailerA wants text books of class 5 and RetailerB be another class also wants text books of
class 5.We can understand that void textbooks is the common feature shared by both retailers.Then consider stationary ,It may include several things like pens,pencils,etc..So,stationary may have different implementation for different retailers, Thus we have one common feature among and one uncommon feature among RetailerA and RetailerB. So,whenever we have a mixture of shareable and non-shareable resources we choose abstract classes.
Suppose RetailerA ask for class 8 textbooks and RetailerB ask for class 6 text books,then even the textbooks method of wholesaler class needs different implementation
depending on the Retailer.
In such issues,void stationary() and void textbooks() must be implemented differently.
So,in this case,we design wholesaler as an interface and RetailerA and RetailerB become implementation classes.
Real World Scenario
class Wholesaler { void textbooks() {} void stationary(); {} }
case 1:
case 2:
In such issues,void stationary() and void textbooks() must be implemented differently.
So,in this case,we design wholesaler as an interface and RetailerA and RetailerB become implementation classes.
Abstract class | Interfaces |
---|---|
1.Abstract keyword is used to declare abstract class. | 1.Interface keyword is used to declare the Interface. |
2.Abstract class contain both abstract methods and non abstract methods. | 2.Interfaces contain only abstract methods. |
3.Abstract class can have final,non-final,static and non-static variables. | 3.Interface has only static and final variables. |
4.We cannot achieve multiple inheritance with abstract classes. | 4.We can achieve multiple inheritance. |
5.An abstract class is used when there are some common features shared by all the objects. | 5.An interface is used when all the features are implemented differently in different objects. |
6.An abstract class can implement an interface. | 6.An interface cannot implement an abstract class. |
No comments:
Post a Comment