This a quick reminder about pros and con's of Java abstract classes and interfaces:
Interface
- A class can implement multiple interfaces
- An interface cannot provide any code at all
- An interface can only define public static final constants
- An interface cannot define instance variables
- Adding a new method has ripple effects on implementing classes (design maintenance)
- JAXB cannot deal with interfaces
- An interface cannot extends or implement an abstract class
- All interface methods are public
In general, interfaces should be used to define contracts (what is to be achieved, not how to achieve it).
Abstract Class
- A class can extend at most one abstract class
- An abstract class can contain code
- An abstract class can define both static and instance constants (final)
- An abstract class can define instance variables
- Modification of existing abstract class code has ripple effects on extending classes (implementation maintenance)
- Adding a new method to an abstract class has no ripple effect on extending classes
- An abstract class can implement an interface
- Abstract classes can implement private and protected methods
Abstract classes should be used for (partial) implementation. They can be a mean to restrain the way API contracts should be implemented.
Nice post. I found one error under the Abstract class section:
ReplyDeleteAn interface can define instance variables.
No you can't, all variables are declared static final in an interface, no matter if the modifiers are there or not. Try to run a program modifying such a variable, the code will not compile.
Deletecheck yo:
DeleteAbstract Class
A class can extend at most one abstract class
An abstract class can contain code
An abstract class can define both static and instance constants (final)
>>>> An interface can define instance variables
Yes, typo. Thanks, fixed it!
Deletenope by default instance varible are static final in interface
DeleteWhat he is saying is that you actually wrote that as the 4th item of the abstract class description.
ReplyDelete