When i need to use abstract class and interface in Java? [duplicate]
Possible Duplicate:
Abstract class and Interface class?
When i need to use abstract class and interface in Java?
My doubt is
- Which situation i need to use abstract class and which situation i need to use interface.
- interface satisfy the abstract class properties. so then why we need especially abstract class?
- i know, that abstract class contains abstract methods and non abstract methods, but we can use abstract class as a ordinary class, then the result will be same in the both classes.开发者_开发问答 the ordinary class also inherited same as abstract class. So why we need abstract class.
If anybody know the good example please reply me.
Thanks.
Another important aspect of abstract class is that unlike interface, adding new methods to it won't break binary compatibility. So, from the API evolution point of view, especially when you can expect additions to the public API, abstract classes are more preferable.
I would say that there are two types of inheritance. One I would say as Implementation Inheritance and other as Contract Inheritance.
Abstract classes are used for having Implementation Inheritance. You can extend/change the behavior of your super/parent class.
Interfaces would go for Contract Inheritance. Where you are more interested in having the class implement some kind of a contract (service methods with arguments - more of a contract) and the behavior is different for different implementation, nothing generic that you can bundle up in an abstract class and extend the behavior.
You need to use abstract classes if you want to apply the template pattern http://en.wikipedia.org/wiki/Template_method_pattern, usually in framework code. As a rule of thumb, if you're not intending to implement the template pattern, you're better off with interfaces, which permit loose coupling, the way spring framework does. Loose coupling leads to a design open to evolutions and a better testability, with techniques like mock objects (http://easymock.org)
精彩评论