Question: When do I to choose an abstract class over an interface?
Answer: Choosing interfaces and abstract classes is not an either/or
"Often in a design, you
want the base class to present only an interface for its derived classes. That
is, you don't want anyone to actually create an object of the base class, only
to upcast to it so that its interface can be used. This is accomplished by
making that class abstract using the abstract keyword. If anyone tries to make
an object of an abstract class, the compiler prevents them. This is a tool to
enforce a particular design.
You can also use the
abstract keyword to describe a method that hasn't been implemented yet-as a stub
indicating "here is an interface function for all types inherited from this
class, but at this point I don't have any implementation for it." An abstract
method may be created only inside an abstract class. When the class is
inherited, that method must be implemented, or the inheriting class becomes
abstract as well. Creating an abstract method allows you to put a method in an
interface without being forced to provide a possibly meaningless body of code
for that method.
The interface keyword
takes the concept of an abstract class one step further by preventing any
function definitions at all. The interface is a very handy and commonly used
tool, as it provides the perfect separation of interface and implementation. In
addition, you can combine many interfaces together, if you wish, whereas
inheriting from multiple regular classes or abstract classes is not possible."
from "Thinking in Java",
Our older tips: March 22, 2001 - October 21, 2002
All published and not published on the site tips read
9 comments | | Score: 3.33